Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Type parameters : How to Parse?

public static T Process<T>(this string key)
        where T:bool,string, DateTime
    {
        var tType = typeof(T);

        if(tType == typeof(DateTime))
        {
            return DateTime.Parse(key.InnerProcess());
        }
        else if(tType == typeof(bool))
        {
            return bool.Parse(key.InnerProcess());
        }
        else if(tType == typeof(string))
        {
            return key.InnerProcess();
        }
    }

It says it cannot typecast from bool to T, or datetime to T.. How to achieve this ?

The innerPrecess() gives me a string. I want to parse it into the given parameter's type and then return it.

like image 630
Bilal Fazlani Avatar asked Dec 12 '25 22:12

Bilal Fazlani


1 Answers

You can use Convert.ChangeType for simpler:

public static T Process<T>( string key) where T: IConvertible
{
    return (T)Convert.ChangeType(key.InnerProcess(), typeof (T));
}
like image 125
cuongle Avatar answered Dec 15 '25 11:12

cuongle



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!