Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a generic constraint so that I can use the ?? coalesing operator

Tags:

c#

generics

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?

like image 352
scott-pascoe Avatar asked Sep 02 '25 18:09

scott-pascoe


1 Answers

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.

like image 199
sll Avatar answered Sep 04 '25 09:09

sll