Generic Class
Let us have a look at the Generic class in C#. Generic classes in C# have type parameters. The generic class introduces a type parameter. This becomes part of the class definition itself. The generic class of Type T is used in the following demo. The letter T denotes a type that is only known based on the calling location.
Open Visual Studio. Select the project type as console application.
Step 1
Click on File -> New -> Project.
Step 2
Select Visual C# from left the hand pane. Choose Console Application in the right side. Name the Project “Generic Class”. Define the desired location to save the project in your hard drive. Click OK.
Step 3
Write the following code in the application.
- public class Myclass<T>
- {
- public void Compareme(T v1, T v2)
- {
- if (v1.Equals(v2))
- {
- Console.Write("The value is matching");
- }
- else
- {
- Console.Write("The value is not matching");
- }
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- Myclass<string> objmyint = new Myclass<string>();
- objmyint.Compareme("Amit","Amit");
- Console.ReadLine();
-
- }
- }
When we run the preceding code we get the following output.
Let us now change the string to something else and check the output. In this scenario I have made my second string parameter “amit”.
- public class Myclass<T>
- {
- public void Compareme(T v1, T v2)
- {
- if (v1.Equals(v2))
- {
- Console.Write("The value is matching");
- }
- else
- {
- Console.Write("The value is not matching");
- }
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- Myclass<string> objmyint = new Myclass<string>();
- objmyint.Compareme("Amit","amit");
- Console.ReadLine();
-
- }
- }
Let us see the output now.