InterviewSolution
| 1. |
How to work with Generics in C#? |
|
Answer» Classes and methods in C# can be created using Generics that defer the specification of TYPES until the class or METHOD is declared. This means that the creation of classes and methods that work with any data type can be handled using Generics. A Generic class can be defined using angle brackets <>. There are type parameters that are Generic. These can handle any data type that is specified in a Generics class. Also, a Generic method is a method that is declared by using type parameters. A program that demonstrates generic class and generic method in C# is given as FOLLOWS: using System; public class GenericClass<T> { private T GenericMember; public GenericClass(T data) { GenericMember = data; } public T GenericMethod(T GenericParameter) { Console.WriteLine("The Generic parameter is: {0}", GenericParameter); return GenericMember; } public T genericProperty { get; set; } } public class Program { public static void Main() { GenericClass<CHAR> GenericObject1 = new GenericClass<char>('D'); GenericClass<int> GenericObject2 = new GenericClass<int>(70); char num1; int num2; Console.WriteLine("For a character variable"); num1 = GenericObject1.GenericMethod('A'); Console.WriteLine("The Generic member variable is: {0}", num1); Console.WriteLine("For an integer variable"); num2 = GenericObject2.GenericMethod(50); Console.WriteLine("The Generic member variable is: {0}", num2); } }The output of the above program is as follows: For a character variable The Generic parameter is: A The Generic member variable is: D For an integer variable The Generic parameter is: 50 The Generic member variable is: 70 |
|