Arli  Chokoev
Arli Chokoev

Reputation: 549

Conversion to generic type

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?

Upvotes: 3

Views: 145

Answers (1)

Guru Stron
Guru Stron

Reputation: 141755

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.

Upvotes: 3

Related Questions