Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
LeftbarAd
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET 2.0/3.5 » Generics in .Net 2.0 made simple

Generics in .Net 2.0 made simple

Generics provide the solution to a limitation in earlier versions of the common language runtime and the C# language in which generalization is accomplished by casting types to and from the universal base type Object. By creating a generic class, you can create a collection that is type-safe at compile-time.

Technologies: .NET 1.0/1.1,Visual C# .NET
Total downloads : 141
Total page views :  7020
Rating :
 0/5
This article has been rated :  0 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
GenericImplementation.zip
 
ArticleAd
Become a Sponsor



Why Generics?

Generics provide the solution to a limitation in earlier versions of the common language runtime and the C# language in which generalization is accomplished by casting types to and from the universal base type Object. By creating a generic class, you can create a collection that is type-safe at compile-time.
By allowing you to specify the specific types acted on by a generic class or method, the generics feature shifts the burden of type safety from developer to the compiler. There is no need to write code to test for the correct data type, because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced.

Also Generics got rid of disadvantage of array list by avoiding the type casting.

Let us go through the simple example with usage of Generics.

Implementation of Generics

The first step in generics is to create the list of generic template for which the class is applicable.

Let us take an example of creating Generic collection using the simple bank requirement below. Requirement is to create the collection of either Current Bank account or Savings bank account.

Create two classes.

  1. Savings bank account
  2. Current Bank account

SavingsBank.cs

using System;

using System.Collections.Generic;

using System.Text;

 

namespace GenericImplementation

{

    class SavingsBank

    {

        protected string name;

        protected int age;

        private const float MIN_AMT_LMT = 10000;

        

        private float  accBalance;

        public SavingsBank(string AccName, int age, string opType, float balanceAmt)

        {

            this.Name = AccName;

            this.Age = age;

            if (opType.ToLower().Equals("credit"))

            {

                this.DoCredit(balanceAmt);

            }

            else

            {

                this.DoDebit(balanceAmt);

            }

        }

        public string Name

        {

         get

          {

            return name;

          }

            set

            { name = value;

            }

        }

 

        public int Age

        {

            get

            {

            return age;

            }

            set

            { age = value;

            }

        }

 

        public float TotalBalance

        {

            get

            {

                return accBalance;

            }

            set

            {

                accBalance = value;

            }

        }

        public void DoCredit(float credBal)

        {

 

            TotalBalance = TotalBalance + credBal;

   

 

        }

        public void DoDebit(float debBal)

        {

            if (TotalBalance - debBal > MIN_AMT_LMT)

            {

            TotalBalance = TotalBalance - debBal;

            }

            else

            {

                throw new Exception("Balance should not be less than minimum amount " + MIN_AMT_LMT.ToString());

 

            }

 

        }

        public override string ToString()

        {

            return " Account name :" + this.Name + " Age:" + this.age.ToString() + " Balance : " + this.TotalBalance.ToString();

        }

    

       

    }

}

Current Bank A/C:

using System;

using System.Collections.Generic;

using System.Text;

 

namespace GenericImplementation

{

    class CurrentBank

    {

        protected string name;

        protected int age;

        private float accBalance;

        private const float MIN_AMT_LMT = 20000;

        public CurrentBank(string AccName, int age,string opType,float balanceAmt)

        {

            this.Name = AccName;

            this.Age = age;

            if (opType.ToLower().Equals("credit"))

            {

                this.DoCredit(balanceAmt);

            }

            else

            {

                this.DoDebit(balanceAmt);

            }

        }

        public string Name

        {

            get

            {

                return name;

            }

            set

            {

                name = value;

            }

        }

 

        public float GetCreditLimit

        {

               get

            {

                return MIN_AMT_LMT;

            }

        }

 

        public int Age

        {

            get

            {

                return age;

            }

            set

            {

                age = value;

            }

        }

        public float TotalBalance

        {

            get

            {

                return accBalance;

            }

            set

            {

                accBalance = value;

            }

        }

        public void DoCredit(float credBal)

        {

 

            TotalBalance = TotalBalance + credBal;

 

        }

        public void DoDebit(float debBal)

        {

            if (TotalBalance - debBal > MIN_AMT_LMT)

            {

                TotalBalance = TotalBalance - debBal;

            }

            else

            {

                throw new Exception("Balance should not be less than minimum amount " + MIN_AMT_LMT.ToString());

 

            }

 

        }

        public override string ToString()

        {

            return " Account name :" +this.Name + " Age:" +this.age.ToString() + " Balance : " + this.TotalBalance.ToString();

        }

    

    }

}
 
Now create a Generic bank account collection which can hold the collection of either Savings Bank account or Current bank account.
 
Generic Bank Collection:

using System;

using System.Collections;

using System.Collections.Generic;

using System.Text;

 

namespace GenericImplementation

{

    class GenericBankCollection<AccountType>  : CollectionBase

    {

        public void Add(AccountType GenericObject)

        {

            InnerList.Add(GenericObject);

        }

 

        public void Remove(int index)

        {

            InnerList.RemoveAt(index);

        }

        public AccountType Item(int index)

        {

            return (AccountType)InnerList[index];

        }

    }
}
 
Usage:

 

Now we can use the Generic bank collection to hold either the savingsBankAccount or CurrentBankAccount collection.

 

Program.cs:


using System;

using System.Collections.Generic;

using System.Text;

 

namespace GenericImplementation

{

    class Program

    {

        static void Main(string[] args)

        {

           GenericBankCollection<SavingsBank> sbAccs = new GenericBankCollection<SavingsBank>();

            sbAccs.Add(new SavingsBank("Sriram",34,"credit",1000));

            sbAccs.Add(new SavingsBank("Saik",30,"debit",1000));

 

            GenericBankCollection<CurrentBank> curAccs = new GenericBankCollection<CurrentBank>();

            curAccs.Add(new CurrentBank("Mohan", 34, "credit", 1000));

            curAccs.Add(new CurrentBank("Krishna", 30, "credit", 1000));

 

            System.Console.WriteLine("Savings Accounts");

            System.Console.WriteLine("=========");

            foreach (SavingsBank savingsBank in sbAccs)

            {

                System.Console.WriteLine(savingsBank.ToString());

            }

 

            System.Console.WriteLine("Current Accounts");

            System.Console.WriteLine("=========");

            foreach (CurrentBank CurrentBank in curAccs)

            {

                System.Console.WriteLine(CurrentBank.ToString());

            }

 

 

            System.Console.ReadLine();

 

    }

    }

}


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Sriram Surapureddy
Surapureddy Sriram is Presently working as Senior Technical lead in HCL technologies,Hyderabad
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
GenericImplementation.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved