This time I'd like to introduce you with a sample code I've written... I'll be talking about creating a method with a generic return type.
Currently, the .Net Framework supports parameter overloading but does not support return type overloading. A method with a generic return type means that you can pass the return type to the method and get the result as this type (SampleMethod<string>() will return a string and SampleMethod<bool>() will return a bool value) - a little workaround for implementing a kind of return type overloading.
It is not really recommended to use this kind of method because of performance issues, but it is a good sample of the great power of Generics.
The declaration of our method is similar to regular method with generic parameters, we just put the return type as the generic type:
public T SampleMethod<T>()
|
Inside the method you code whatever you want to code, the only difference lies within the last lines, where you return a value to the caller.
There we should find out what is the requested return type, and generate a relevant return value. Then we should convert the return value to T which is the return type:
Type retType = typeof(T);
if (retType == typeof(bool))
{
return (T)Convert.ChangeType(true, retType);
}
|
On the first line I put the requested return value in a local variable.
On the second line, I compare the requested return type with a boolean type, which we support for this sample method.
On the fourth line, I convert the return value (true) to the requested return type. I had to do this so the compiler will be satisfied that I give the caller method the type of its desire.
Now all we have to do is to call our method, asking it to return us a boolean value:
Console.WriteLine(SampleMethod<bool>());
|
In conclusion, this method can be used in really extreme cases. For instance, if you want to create one method that searches for a specific value in a list. You want to know if the value exists for once (return bool value), and you want to know the indexes where the value exists for once (return a list).
You should avoid using this though. It is recommended to separate this kind of method to various different methods in order to ease code reviews and improve performance.
Shay.
The whole class:
public class SampleClass
{
public SampleClass()
{ }
public void RunMethod()
{
try
{
Console.WriteLine(SampleMethod<bool>());
Console.WriteLine(SampleMethod<string>());
Console.WriteLine(SampleMethod<float>());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public T SampleMethod<T>()
{
/*
Do something...
*/
Type retType = typeof(T);
if (retType == typeof(bool))
{
return (T)Convert.ChangeType(true, retType);
}
else if (retType == typeof(string))
{
return (T)Convert.ChangeType("Something to return", retType);
}
else
{
throw new NotSupportedException(typeof(T).FullName + " is not supported");
}
}
}
|