Sirop4ik
Sirop4ik

Reputation: 5253

How to cast generic TYPE in right way?

I have such method

        public TYPE GetParam<TYPE>(ICacheKey key)
        {
            var result = default(TYPE);

            if (typeof(TYPE) == typeof(string))
            {
                result = m_AppConfigCache.GetParamString(key.GroupName, key.Key);
            }
            else if (typeof(TYPE) == typeof(bool))
            {
                result = m_AppConfigCache.GetParamBool(key.GroupName, key.Key);
            }

            return result;
        }

So, I check if type is (for example) string and if yes I have to call one method, if type is bool so another

This method

m_AppConfigCache.GetParamString(key.GroupName, key.Key)

returns string, but I get an error that TYPE is not string and it could not be casted...

Question is - how to do it?

Upvotes: 0

Views: 97

Answers (1)

Rekshino
Rekshino

Reputation: 7325

You can write such a method if you do cast returned object to object first and then to the TYPE:

public TYPE GetParam<TYPE>(ICacheKey key)
{
    if (typeof(TYPE) == typeof(string))
    {
        return (TYPE)((object)m_AppConfigCache.GetParamString(key.GroupName, key.Key));
    }
    else if (typeof(TYPE) == typeof(bool))
    {
        return (TYPE)((object)m_AppConfigCache.GetParamBool(key.GroupName, key.Key));
    }

    return default(TYPE);
}

Upvotes: 1

Related Questions