Search code examples
c#genericstype-constraints

Multiple constraint on type parameter


I did this multiple constraint

public class BaseValidation<S, R> 
        where R : BaseRepository 
        where S : BaseService<R>, new()
    {
        public S service;

        public BaseValidation()
        {
            service = new S();
        }
    }

Here's the BaseService class

public class BaseService<T> where T : BaseRepository, new(){ }

And when I build, an error occurs like this...

'R' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type

How to properly done this? Thank you.


Solution

  • You need to add the new() constraint to R as well, since T has that constraint in the definition of BaseService<T>:

    public class BaseValidation<S, R> 
            where R : BaseRepository, new()
            where S : BaseService<R>, new()
    {
        public S service;
    
        public BaseValidation()
        {
            service = new S();
        }
    }
    

    If you don't actually need that constraint in BaseService<T>, just remove it.