Friday, May 20, 2011

C# and .NET interview Question - Explain about the Generics?

Answer:

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.

    class Check<UNKNOWNDATATYPE>
  {
      public bool Compare(UNKNOWNDATATYPE i, UNKNOWNDATATYPE j)
      {
          if (i.Equals(j))
          {
              return true;
          }
          else
          {
              return false;
          }
      }
  }

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).

    class Program
  {
      static void Main(string[] args)
      {
          Check ObjCheck = new Check();    //here i have defined int datatype
          bool b1 = ObjCheck.Compare(1, 1);
          Check Obj1 = new Check();    //here i have defined string datatype
          bool b2 = Obj1.Compare("feroz", "kalim");
          Console.WriteLine("Numeric Comparison Result:" + b1);
          Console.WriteLine("String Comparison Result:"+ b2);
          Console.ReadLine();
      }
  }

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

    class Program
  {
      static void Main(string[] args)
      {
          Check ObjCheck = new Check();
          bool b1 = ObjCheck.Compare(1, 1);
          Check Obj1 = new Check();
          bool b2 = Obj1.Compare("feroz", "kalim");
          Console.WriteLine("Numeric Comparison Result:" + b1);
          Console.WriteLine("String Comparison Result:"+ b2);
          Console.ReadLine();
      }
  }

  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# and Dotnet interview questions

Regards,

Visit Authors blog for more Most asked Dotnet interview questions

No comments: