Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a generic function in c#?

Tags:

c#

generics

I am trying to write a generic function in c# which tries to parse a string based on the type.

Here is what I tried

    public static T convertString<T>(string raw)
    {
        if( typeof(T) == DateTime ){
            DateTime final;
            DateTime.TryParseExact(raw, "yyyy-mm-dd hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out final);
            return final;
         }

        if( typeof(T) == int ){
            int final;
            Int32.TryParse(raw, out final);
            return final;
        }

    }

How can I correct this function to work?

like image 285
Junior Avatar asked Jun 23 '26 07:06

Junior


1 Answers

you can try something like that :

public static T ConvertFromString<T>(string raw)
{
    return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(raw);
}

// Usage
var date = ConvertFromString<DateTime>("2015/01/01");
var number = ConvertFromString<int>("2015");

Edit: Support for TryConvert

Otherwise you can create a function that will try to convert the input string:

public static bool TryConvertFromString<T>(string raw, out T result)
{
    result = default(T);
    var converter = TypeDescriptor.GetConverter(typeof (T));
    if (!converter.IsValid(raw)) return false;

    result = (T)converter.ConvertFromString(raw);
    return true;
}

// Usage
DateTime result;
if (!TryConvertFromString<DateTime>("this is not a date", out result))
{

}
like image 198
Thomas Avatar answered Jun 24 '26 21:06

Thomas



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!