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 TDatabase
is a reference type
where TDatabase : class, IDatabase
MSDN, Constraints on Type Parameters (C# Programming Guide)
where T : class The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.
MSDN, ?? Operator (C# Reference):
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With