How do I define a generic constraint so I can use the coalescence operator
I am 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 line, the return db ?? (db = DatabaseFactory.Get());
compiler complains about "Left operand" ?? "operator must have a reference or null type"
I understand the error, but I don't know how to set a constraint on the TDatabase type parameter so that the compiler knows it is a reference or null type.
How to make the compiler happy?
source to share
You must specify what TDatabase
is the reference type
where TDatabase : class, IDatabase
MSDN, Restrictions on Type Parameters (C # Programming Guide)
where T: class The type argument must be a reference type; this also applies to any class, interface, delegation, or array type.
MSDN, ?? Operator (C # reference) :
the operator is called the null coalescing operator and is used to define a default value for null value types or reference types. This returns the left-hand operand if the operand is non-zero; otherwise, it returns the right-hand operand.
source to share