Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Current Affairs » 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.

Page Views : 49264
Downloads : 754
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
GenericImplementation.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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();

 

    }

    }

}

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
Thanks by din On March 22, 2010
Yes it is useful for me.
Reply | Email | Modify 
Very good by harish On February 7, 2011
I here download your zip file and without seeing anything I run the app and got an exception in saving.cs that is-balance should not be less than 1000
Reply | Email | Modify 
Too lengthy.. by sanjay054 On March 18, 2011
Code example too lengthy for a starter to understand..
Reply | Email | Modify 
s by Rakesh On June 1, 2011
s
Reply | Email | Modify 
Very useful.....with a question by richard On December 6, 2011
How to modify content? After adding the record, I need to modify record later on, what the best way to do this?
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.