How to make a Generic Type Cast function

C#.NetGenerics

C# Problem Overview


> Possible Duplicate:
> is there a generic Parse() function that will convert a string to any type using parse?

I want to make a generic function for doing some operations, like:

ConvertValue<T>(string value)

If T is int then the function will convert the value to int and return the result.

Similarly, if T is boolean, the function will convert the value to boolean and return it.

How to write this?

C# Solutions


Solution 1 - C#

Something like this?

public static T ConvertValue<T>(string value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}

You can then use it like this:

int val = ConvertValue<int>("42");

Edit:

You can even do this more generic and not rely on a string parameter provided the type U implements IConvertible - this means you have to specify two type parameters though:

public static T ConvertValue<T,U>(U value) where U : IConvertible
{
    return (T)Convert.ChangeType(value, typeof(T));
}

I considered catching the InvalidCastException exception that might be raised by Convert.ChangeType() - but what would you return in this case? default(T)? It seems more appropriate having the caller deal with the exception.

Solution 2 - C#

While probably not as clean looking as the IConvertible approach, you could always use the straightforward checking typeof(T) to return a T:

public static T ReturnType<T>(string stringValue)
{
	if (typeof(T) == typeof(int))
		return (T)(object)1;
	else if (typeof(T) == typeof(FooBar))
		return (T)(object)new FooBar(stringValue);
	else
		return default(T);
}

public class FooBar
{
	public FooBar(string something)
	{}
}

Solution 3 - C#

ConvertValue( System.Object o ), then you can branch out by o.GetType() result and up-cast o to the types to work with the value.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRizView Question on Stackoverflow
Solution 1 - C#BrokenGlassView Answer on Stackoverflow
Solution 2 - C#BrandonAGrView Answer on Stackoverflow
Solution 3 - C#m1tk4View Answer on Stackoverflow