Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rules for Inheriting class

Tags:

c#

inheritance

Can I set rules for the class inheriting my base class. eg. Person : BaseClass, I want Person to implement iSomeKindOfInterface, if Person does not implement the interface, it is not allowed to inherit from BaseClass.

I know this is posibble in generic base classes where you can do the following

public BaseClass<T>
     where T : iSomeKinfOfInterface
like image 736
Captain0 Avatar asked Feb 17 '12 09:02

Captain0


People also ask

What happens when a class is inherited?

Inheritance is a feature or a process in which, new classes are created from the existing classes. The new class created is called “derived class” or “child class” and the existing class is known as the “base class” or “parent class”. The derived class now is said to be inherited from the base class.

How do you inherit a class?

Inheritance enables you to create new classes that reuse, extend, and modify the behavior defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class.

What is class inheritance example?

In this, various Child classes inherit a single Parent class. The example given in the introduction of the inheritance is an example of Hierarchical inheritance since classes BMW and Audi inherit class Car. Here two child classes are inheriting the same Parent class.


2 Answers

You can implement the interface in your base class and force the inheriting class to supply the implementation:

public interface ISomeInterface
{
    void DoSomething();
}

public abstract class BaseClass : ISomeInterface
{
    public abstract void DoSomething();
}

public class Person : BaseClass
{
    public override void DoSomething()
    {
        ...
    }
}
like image 154
Trevor Pilley Avatar answered Sep 28 '22 04:09

Trevor Pilley


Declare your class as

abstract BaseClass : ISomeKinfOfInterface
like image 39
Maheep Avatar answered Sep 28 '22 03:09

Maheep