Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion to generic type

Tags:

c#

I have following property in C#:

public T Value
{
    get
    {
        ClassImNotAllowedToChange.GetValue<T>();
    }
    set
    {
        ClassImNotAllowedToChange.SetValue<T>(value);
    }
}

For some reasons I can't change the implementation of ClassImNotAllowedToChange, it may impose some limitations on my part of code. The problem here is that I want to save and read TimeSpan as seconds amount, converted to int. And while I can easily write whatever I want in setter, getter restricts me to use only generic type T, which makes impossible something like this:

get
{
    if (typeof(T) == typeof(TimeSpan))
        return (T)TimeSpan.FromSeconds(ClassImNotAllowedToChange.GetValue<int>());

    return PlcItem.GetValue<T>();
}

There is no implicit conversion from int to TimeSpan, so the first code listing causes an InvalidCastException in runtime. Is there any workaround to convert int to TimeSpan within getter or it's better to find another way of implementation?

like image 760
Arli Chokoev Avatar asked Feb 18 '26 02:02

Arli Chokoev


1 Answers

As workaround you can cast TimeSpan.FromSeconds to object and then to T (with corresponding performance hit):

get
{
    if (typeof(T) == typeof(TimeSpan))
        return (T)(object)TimeSpan.FromSeconds(ClassImNotAllowedToChange.GetValue<int>());

    return PlcItem.GetValue<T>();
}

But I would recommend to rework your code somehow so you will not need to do this.

like image 130
Guru Stron Avatar answered Feb 19 '26 16:02

Guru Stron



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!