Page Stats
Visitor: 180
C#.Net Generics
Generics is not a completely new concept, similar concept exist with other languages also. In C++, templates can be compared to generics. Generics allow you to define a class with some specific data type at compile time. A generic class can be defined using angle brackets <>.
Example 1: C#.Net Generic
namespace ConsoleApplication1 { class example<t> { public void square(t num) { if (num.GetType().ToString() == "System.Int32") { int n = Convert.ToInt32(num.ToString()); Console.WriteLine("Square of 10 is " + n * n); } else { Console.WriteLine("Invalid Number:" + num); } } } class Program { static void Main(string[] args) { example<int> ex = new example<int>(); ex.square(10); example<string> ex2 = new example<string>(); ex2.square("abc"); Console.ReadKey(); } } }

Advertisement