chuckd
chuckd

Reputation: 14530

Can I have multiple class constraints without setting the constraint to a type 'class' in C#

I have this class, it's part of my specification pattern. Following this link

public class SpecificationEvaluator<TEntity> 
   where TEntity : BaseEntity

and BaseEntity consists of just the id

ex.

public class BaseEntity
{
   public int Id { get; set; }
}

and this works fine for all my entities that inherit 'BaseEntity'

ex.

Product : BaseEntity
Invoice : BaseEntity
Message : BaseEntity

now I want to use the specification pattern on my 'User' entity, so that I can provide specs/conditions and fetch lists of users.

But my problem is my projects 'User' entity doesn't inherit 'BaseEntity', it inherits 'IdentityUser'

ex.

public class User : IdentityUser<int>
{
}

I'm aware I can't have multiple classes as constraints, but I can have multiple interfaces.

I know I can set the constraint to just a 'class'

ex.

public class SpecificationEvaluator<TEntity> 
where TEntity : class
{
}

but doesn't this sorta defeat the purpose of creating specific constraints?

QUESTION - Is there another solution I can implement to have both 'BaseEntity' and 'User' as constraints?

Upvotes: 0

Views: 110

Answers (1)

Enigmativity
Enigmativity

Reputation: 117027

It seems to me that you might have to do this:

public interface IIdentityUser<T>
{
    T Id { get; set; }
}

public class SpecificationEvaluator<TEntity, T>
    where TEntity : IIdentityUser<T>
{ }

public class BaseEntity : IIdentityUser<int>
{
    public int Id { get; set; }
}

public class Product : BaseEntity { }
public class Invoice : BaseEntity { }
public class Message : BaseEntity { }

public class IdentityUser<T> : IIdentityUser<T>
{
    public T Id { get; set; }
}

public class User : IdentityUser<int>
{
}

Upvotes: 1

Related Questions