Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




C# and .NET interview Question - Define Generic?

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#/ .NET interview questions

Regards,

Visit Authors blog for more C# and .NET interview questions

 

Share this article   |    Print    |    Article read by 6753 times
Author:
Shivprasad koirala Koirala
I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. Do visit my site http://www.questpond.com for .NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers
Related Articles: No related article
Related Interview Questions: