Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 1 year ago 84
C# Question

T type default value

I had several Extension Methods like

. now I'm trying to make a single extension method for all of them. the problem is that to make the
parameter optional I have to give it a value like
T Default = 0
, but it generates the error:

A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'T'

If I use it like
T Default = (T)0
then I get another error:

Cannot convert type 'int' to 'T'

This is my extension method:

public static T Parse<T>(this string x, T Default = 0)
Type type = typeof(T);
if(type == typeof(int))
{ if(!string.IsNullOrEmpty(x) int.TryParse(x , out Defualt); return Default; }

Answer Source

You can just use default(T) instead:

public static T Parse<T>(this string x, T defaultValue = default(T))

However, I would strongly question the design here - you're not really writing a generic method, but a method which accepts one of a specific set of types and treats each one differently. There are times where this is enforced on you, but I'd typically have a Dictionary<T, SomeDelegate> to try to handle it more cleanly.

In addition, you're still going to have problems calling int.TryParse - you can't use the parameter to Parse<T> as an argument - you'd need something like:

if (typeof(T) == typeof(int))
    // You need to consider what you want to happen if
    // int.TryParse returns false - do you want to return 0,
    // or defaultValue?
    int ret;
    if (int.TryParse(x, out ret))
        // Annoying but required due to which conversions are available
        return (T)(object) ret;
return defaultValue;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download