Mar 26, 2009

Generic method

The following code shows some example of generic method

//the T can be inferred from the type of input parameter
public static T DoByInferType<t>(T input)
    return default(T);

//the Toutput cannot be inferred by the input parameter
public static Toutput DoByExplicitType<Tinput, Toutput>(Tinput input)
    return default(Toutput);

int result = Utililty.DoByInferType(1);
//or (the <int> is optional)
//int result = Utililty.DoByInferType<int>(1);

//<string, int> has be explicit
int result2 = Utililty.DoByExplicitType<string, int>("1");

List<string> l = new List<string>();

Converter<string, int> converterUsingDelegate = delegate(string theString)
    return int.Parse(theString);

//public List<toutput> ConvertAll<toutput>(Converter<T, TOutput> converter);
//the TOutput can be inferred from the input paramether
List<int> intList1 = l.ConvertAll(converterUsingDelegate);