What does "The type T must be a reference type in order to use it as parameter" mean?

C#GenericsController

C# Problem Overview


I'm trying to create a generic controller on my C#/MVC/Entity Framework application.

public class GenericRecordController<T> : Controller
{
    private DbSet<T> Table;
    // ... 

    public action()
    {
        // ... 
        db.Entry(T_Instance).State = System.Data.Entity.EntityState.Modified;
    }
}

However the DbSet<T> and T_Instance line has a compiler error.

> The type T must be a reference type in order to use it as parameter.

When I constrain it as a class, it was solved.

Controller where T : class

What does the error mean? I'm not asking for a solution, I would like to understand why this error occurs and why constraining it as a class solves it.

C# Solutions


Solution 1 - C#

If you look at the definition of DbSet<TEntity>:

public class DbSet<TEntity> : DbQuery<TEntity>, IDbSet<TEntity>, IQueryable<TEntity>, IEnumerable<TEntity>, IQueryable, IEnumerable, IInternalSetAdapter 
where TEntity : class

Because it has a type constraint that the generic type must be a class then you must initialize it with a type that also matches this condition:

public class GenericRecordController<T> : Controller where T : class
{ ... }

Solution 2 - C#

They apparently have a constraint on the generic type.

All you need to change is:

public class GenericRecordController<T> : Controller where T : class

This tells the compiler that only reference types may be supplied as a type for T.

Solution 3 - C#

You can do it on just a method as well:

public bool HasKey<T>(T obj) where T : class
{
    return _db.Entry<T>(obj).IsKeySet;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel SantosView Question on Stackoverflow
Solution 1 - C#Gilad GreenView Answer on Stackoverflow
Solution 2 - C#C.EvenhuisView Answer on Stackoverflow
Solution 3 - C#Dave ت MaherView Answer on Stackoverflow