I\'ve got two generic base classes. The second generic class has a constraint on its parameter of the first class.
abstract class FirstClass {...}
If you are actually using the generic type arguments to FirstClass
(as, from your edit, it sounds like you are), then no, what you're looking for is unfortunately not possible. The compiler does not differentiate between type arguments that are related and those that are not.
This is actually an answer to Interface with two generic parameters, solve one automatically which has been marked as duplicate of this question.
You could declare a bunch of interfaces with a specific Id type. Not a perfect solution, but simplifies the declaration of entity classes.
public interface IIntPersistentEntityService<TPersistentEntity>
: IPersistentEntityService<TPersistentEntity, int>
where TPersistentEntity : IPersistentEntity<int>
{
}
public interface IStringPersistentEntityService<TPersistentEntity>
: IPersistentEntityService<TPersistentEntity, string>
where TPersistentEntity : IPersistentEntity<string>
{
}
Then the User
class can be declared like this:
public class UserService : IIntPersistentEntityService<User>
{
public User Get(int id)
{
throw new NotImplementedException();
}
}
You will get a compiler error if you have not the matching Id type.
Create an interface that FirstClass implements. Then you can constrain SecondClass to the interface.
In my experience it is easiest to create non-generic interface to generic classes. It also solves the problem when you need to cast to the base class without knowing the generic type.
interface IFirstClass {...}
abstract class FirstClass<T> : IFirstClass {...}
abstract class SecondClass<T> where T : IFirstClass {...}