Home > Blockchain >  Generic method in C# containing reference to member of generic type (class)
Generic method in C# containing reference to member of generic type (class)

Time:08-19

I try to write generic method and try to express constrain about member of generic type.

private async Task<T> FindOrAdd<T>(DbSet<T> dbSetOfT, string name) where T : class
    {
        var result = await dbSetOfT.FirstOrDefaultAsync(c => c.Name = name);
        return result ?? new T { Name = name };
    }

Is it possible to do this?

CodePudding user response:

This is possible using a interface. I have added the interface to the criteria of T and also added new() To make New T possible

private async Task<T> FindOrAdd<T>(DbSet<T> dbSetOfT, string name) where T 
: class,IName,new()
{
    var result = await dbSetOfT.FirstOrDefaultAsync(c => c.Name == name);
    return result ?? new T { Name = name };
}

public interface IName
{
    public string Name{get;set;}
}
  • Related