Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce arbitrary function on C# generic type

Tags:

c#

generics

I am trying to create a generic function like this, which I plan to instantiate with basic types, mostly DateTime, int and string.

static T MyParameter<T>(string value, T defaultValue)
{
    return value.StartsWith("$$") ? defaultValue : T.Parse(value);
}

This won't compile as there is no guarantee that T will have "Parse".

Is there a "direct" way to implement it? (I mean, avoiding reflection or delegates to do the dirty work).

I can't find any constraint to T that would do the trick.

like image 525
jeanluc orsai Avatar asked Jul 27 '26 17:07

jeanluc orsai


1 Answers

You could pass in the parse method for the generic case:

static T MyParameter<T>(string value, T defaultValue, Func<string, T> parse)
{
    return value.StartsWith("$$") ? defaultValue : parse(value);
}

But for convenience, you probably want to provide overloads for the most common types you plan to use:

static int MyParameter(string value, int defaultValue)
{
    return MyParameter(value, defaultValue, int.Parse);
}
static DateTime MyParameter(string value, DateTime defaultValue)
{
    return MyParameter(value, defaultValue, DateTime.Parse);
}
static string MyParameter(string value, string defaultValue)
{
    return MyParameter(value, defaultValue, x => x);
}

If you really don't like this, you could use reflection, though I wouldn't recommend it:

static T MyParameter<T>(string value, T defaultValue)
{
    if (value.StartsWith("$$"))
    {
        return defaultValue 
    }

    var method = typeof(T).GetMethod("Parse", new[] { typeof(string) });
    return (T)method.Invoke(null, new[] { value });
}
like image 81
p.s.w.g Avatar answered Jul 29 '26 07:07

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!