C# Generic Methods
As we can store different types of data using our generic classes, we can also perform different operations on this data using "Generic Methods". The common error while using generic is that developer tries to perform arithmetic operations on "generic data", without considering the fact that C# is type safe J
Following is an example of Generic methods, which accepts two parameters of same-type and returns its "Addition". For simplicity of example I have create a static method, otherwise there is no specific needJ. Following methods checks that if passed parameters are of "integer type" then convert them to "integer", returns "integer", otherwise convert passed parameters to "String" and returns "concatenated string". (Obviously if you will try to check float, double or other data types in this example, function will CRASH!!)
public static MyDataType Add
{
if (x is Int32)
{
return (MyDataType)System.Convert.ChangeType(System.Convert.ToInt32(x) + System.Convert.ToInt32(y), typeof(MyDataType));
}
else
//Consider it a string
{
return (MyDataType)System.Convert.ChangeType(System.Convert.ToString(x) + System.Convert.ToString(y), typeof(MyDataType));
}
}
To test this function, following is "Test Function:
static void Main(string[] args)
{
Console.WriteLine(@"Addition of <<<{0}>>> and <<<{1}>>> yields <<<'{2}'>>>", 100, 200, Add<Int32>(100, 200));
Console.WriteLine(@"Addition of <<<{0}>>> and <<<{1}>>> yields <<<'{2}'>>>, ",@"C# Generic Method", @" Example", Add<string>("C# Generic Method", " Example"));
Console.ReadKey();
}
And output of this test function is:
Addition of <<<100>>> and <<<200>>> yield <<<'300'>>>
Addition of <<>> and <<>> yield <<<'C# Generic Method Example'>>>
(Note for C# generic classes/introduction to generic class please check blog entry "C# Generics – (Generic Classes)"
No comments:
Post a Comment