Given Expression is Never of the Provided Type

When using generics, and you get an error "Given Expression is Never of <X> Type", it is usually how it is assigned.  For example, I was trying to do this:

public IInterface<T> CreateProvider<T>()
{
    if (typeof(T) is ObjectA)
       return new ObjectAProvider() as IInterface<T>;
    .
    .
    .
    else
       throw new NotImplementedException();

This was a problem; I got the above error.  When digging for an answer, I found this as the solution:  http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=111314&SiteID=1   Type has an IsAssignableFrom method, which I was able to do successfully:

if (typeof(T).IsAssignableFrom(typeof(ObjectA)))
    return new ObjectAProvider() as IInterface<T>;
.
.
.
else
    throw new NotImplementedException();

 

Comments

No Comments

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.