I've been in an interview recently where interviewer asked me this question-
How to write an interface so that it restricts or enforces to be implemented by only a generic type or prevent providing implementation?
Could somebody please answer this question with some code sample or provide any reference of the exactly same question with sample snippets for understanding. Is it possible? If YES then how and If NO then why?
It is not possible to restrict who implements your interface.
The only restriction you can give is for the interface to be generic
public interface IInterface<T> { }
And you can also restrict the generic T
of the interface to some type.
public interface IInterface<T> where T : GenericConstraint { }
This GenericConstraint
restriction can also be the following:
For more info on the constraints available see MS Docs - Constraints on type parameters
As @Saruman has pointed out, it is highly recommended to read:
MS Docs - Generics (C# Programming Guide)
If you use a specific class name:
The type argument must be or derive from the specified base class.
Therefore if I have the following classes:
public class GenericConstraint { }
public class NewGenericConstraint : GenericConstraint{ }
I could provide both GenericConstraint
and NewGenericConstraint
to IInterface<T> where T : GenericConstraint
because both of those are or derive from GenericConstraint
.
Therefore the following classes would be valid:
public class Subject : IInterface<GenericConstraint> { }
public class Subject : IInterface<NewGenericConstraint> { }
public class Subject<T> : IInterface<T> where T : GenericConstraint { }
public class Subject<T> : IInterface<T> where T : NewGenericConstraint { }
The GenericConstraint
cannot be a sealed-class because if GenericConstraint
was sealed, eg:
public sealed class GenericConstraint { }
You wouldn't be able to inherit from it, and the following would fail to compile:
public class NewGenericConstraint : GenericConstraint { }
Therefore, it would be pointless to provide a generic parameter of which constraint is a sealed class. Therefore the compiler enforces you to constrain a generic type to a non-sealed class
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.