Reputation: 749
How to define a must inherit class? in C#
Upvotes: 24
Views: 33230
Reputation: 1873
An interface would be best.
If you need to simulate the functionality , and its not a requirement that it fail at compile time...
define a method in the base class. Throw a an exception as the only line in the implementation. You might want to make the message very very clear about what the problem is.
override the method in the super class(es) and implement them. If you fail to implement in a super class, you will get the exception.
Not perfect, but say you are trying to port code from vb.net... this could work.
Upvotes: 0
Reputation: 51
If u want to create a class, that has to be inherited, you'll need to mark it with the abstract
modifier.
public abstract MyClass
{
}
Upvotes: 5
Reputation: 62246
It's not possible enforse needness of derivation or implementation in code, if that was a question.
But:
You can define an interface
to force consumer to implement it.
Or you can define abstract class
with only abstract members to force consumer to override all of them.
Hope this helps.
Upvotes: 2
Reputation: 7299
Use the abstract
modifier.
public abstract class MyClass()
{
...
}
Upvotes: 9
Reputation: 39013
You can define a class as abstract
, or give it a protected-only constructor. abstract
is better.
Upvotes: 5
Reputation: 498992
You mark the class as abstract
(this is the C# analogue to the VB.NET Must Inherit
).
This will ensure it can't be instantiated directly.
From the linked MSDN article:
The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.
(emphasis mine)
Upvotes: 55