Shivprasad Koirala
C# and .NET interview Question - Explanation on Generic?
By Shivprasad Koirala in ASP.NET on May 20 2011
  • Shivprasad Koirala
    May, 2011 20

    This is one of the most important typical question, which is asked in most of the interviews to check whether you know about generic.

    Generic: Generic help us to create flexible strong type collection.

    Generic basically seperate the logic from the datatype in order maintain better reusability, better maintainability etc.

    Lets see an simple example to understand how exactly generic seperate logic from datatype.

    In order to use Generic in your project you will first have to ensure that you have imported “System.Collections.Generic” namespace.

    1. class Check<UNKNOWNDATATYPE>
    2. {
    3. public bool Compare(UNKNOWNDATATYPE i, UNKNOWNDATATYPE j)
    4. {
    5. if (i.Equals(j))
    6. {
    7. return true;
    8. }
    9. else
    10. {
    11. return false;
    12. }
    13. }
    14. }

    In above code snippet, i have created a class called as “Check” with UNKNOWNDATATYPE so that, i can define different data types at run time. Now, in below code you can see that i have created two object of Check class with two different datatypes(int,string).

    1. class Program
    2. {
    3. static void Main(string[] args)
    4. {
    5. Check ObjCheck = new Check(); //here i have defined int datatype
    6. bool b1 = ObjCheck.Compare(1, 1);
    7. Check Obj1 = new Check(); //here i have defined string datatype
    8. bool b2 = Obj1.Compare("feroz", "kalim");
    9. Console.WriteLine("Numeric Comparison Result:" + b1);
    10. Console.WriteLine("String Comparison Result:"+ b2);
    11. Console.ReadLine();
    12. }
    13. }

    Below is the full code snippet for the same so that you can try it by yourself and see the resultant output.

    1. class Program
    2. {
    3. static void Main(string[] args)
    4. {
    5. Check ObjCheck = new Check();
    6. bool b1 = ObjCheck.Compare(1, 1);
    7. Check Obj1 = new Check();
    8. bool b2 = Obj1.Compare("feroz", "kalim");
    9. Console.WriteLine("Numeric Comparison Result:" + b1);
    10. Console.WriteLine("String Comparison Result:"+ b2);
    11. Console.ReadLine();
    12. }
    13. }
    14. class Check<UNKNOWNDATATYPE>{public bool Compare(UNKNOWNDATATYPE i, UNKNOWNDATATYPE j){if (i.Equals(j)){return true;}else{return false;}}}

    For more information about generic, please watch the below video.
    Please click here to see more C#/ .NET interview questions

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS