A simple generic class : Generic Class « Generics « C# / C Sharp






A simple generic class

A simple generic class
 
using System;

class MyGenericClass<T> {
  T ob;

  public MyGenericClass(T o) {
    ob = o;
  }

  public T getob() {
    return ob;
  }

  public void showType() {
    Console.WriteLine("Type of T is " + typeof(T));
  }
}

public class Test {
  public static void Main() {
    MyGenericClass<int> iOb;

    iOb = new MyGenericClass<int>(102);

    iOb.showType();

    int v = iOb.getob();
    Console.WriteLine("value: " + v);

    MyGenericClass<string> strOb = new MyGenericClass<string>("Generics add power.");
    strOb.showType();
    
    string str = strOb.getob();
    Console.WriteLine("value: " + str);
  }
}

           
         
  








Related examples in the same category

1.Declare the generic class.
2.A Generic Class with Two Type ParametersA Generic Class with Two Type Parameters
3.Generic Fields
4.Create relationship between two type parameters
5.Demonstrate the default keywordDemonstrate the default keyword
6.Comparing Instances of a Type ParameterComparing Instances of a Type Parameter
7.'This' Reference for Generic Types
8.Generic class with interfaceGeneric class with interface