I’m trying to define a generic class
public abstract class RepositoryBase<TDatabase, TKey, T> : IRepository<TKey, T>
where T : class
where TDatabase : IDatabase
{
private TDatabase db;
private readonly IDbSet<T> dbset;
protected IDatabaseFactory<TDatabase> DatabaseFactory { get; private set; }
protected TDatabase Database
{
get
{
return db ?? (db = DatabaseFactory.Get());
}
}
...
}
On the line return db ?? (db = DatabaseFactory.Get());, the compiler is complaining with “Left operand of the ‘??’ operator should be of reference or nullable type”
I understand the error, but don’t know how to put a constraint on the TDatabase type parameter so that the compiler knows it is a reference or nullable type.
How to I make the compiler happy?
You have to indicate that
TDatabaseis a reference typeMSDN, Constraints on Type Parameters (C# Programming Guide)
MSDN, ?? Operator (C# Reference):