Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you wrap the 'Convert' class into a Generic function

Tags:

c#

.net

generics

Below is a simplified example of what I want to do. In the actual code I catch exceptions to do other things. But essentially I would like to wrap the 'Convert' class in a generic function, but alas this code generates an error saying that it cannot implicitly convert from type 'ushort' to 'T'.

Any ideas gratefully received. (It's my first question so go gentle with me!)

    private T ChangeValue<T>(T value, string x)
    {
        if (typeof(UInt16) == typeof(T))
        {
            value = Convert.ToUInt16(x);
        }
        return value;
    }
like image 556
diversemix Avatar asked Mar 27 '26 00:03

diversemix


1 Answers

Are you looking for something like this?

private T ChangeType<T>(object value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}

Usage:

double result = ChangeType<double>(true);
like image 198
dtb Avatar answered Mar 28 '26 13:03

dtb



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!