Search code examples
c#genericstypescastingfactory-pattern

Convert a Type to a Generic constrained T


I am trying to build a Factory which will supply a single factory method. In this method I want to verify whether the incoming Type is the factory's T.

What I've written is simply not working. I believe I understand the reason for it's failure, yet I am not sure how to form my casting correctly.

Below is my code. Any ideas as for how to form this condition/casting?

    public T GetFeature(Type i_FeatureType, User i_UserContext)
    {
        T typeToGet = null;

        if (i_FeatureType is T) // <--condition fails here
        {
            if (m_FeaturesCollection.TryGetValue(i_FeatureType, out typeToGet))
            {
                typeToGet.LoggenInUser = i_UserContext;
            }
            else
            {
                addTypeToCollection(i_FeatureType as T, i_UserContext);
                m_FeaturesCollection.TryGetValue(typeof(T), out typeToGet);
                typeToGet.LoggenInUser = i_UserContext;
            }
        }

        return typeToGet;
    }

Solution

  • Use:

     if (typeof(T).IsAssignableFrom(i_FeatureType))
    

    Instead of:

    if (i_FeatureType is T)