What is MultiLayer Inheritence in C#? - c#

Is it like a class can inherit from both an Interface and a base class?

Probably you mean multilevel inheritance, but it's just a chain of classes inheriting, starting from some base class.
It's like this example class structure:
public class Vehicle { ... } // base class
public class CombustionVehicle : Vehicle { ... } // intermediary class
public class Truck : CombustionVehicle { ... } // derived class
The Truck instance is still a Vehicle, so it still can use it's properties and methods (of course if the access modifier allows it).

I think you are confused here by the term multi layer.
multiple inheritance is not supported in C#. A class cannot directly inherit from more than one base class.
C# supports multilevel inheritance, which means that a class can inherit from a class that itself inherits from another class. For example:

Related

Why is an Array an abstract class in C#? [duplicate]

The C# spec, section 10.1.1.1, states:
An abstract class is permitted (but
not required) to contain abstract
members.
This allows me to create classes like this:
public abstract class A
{
public void Main()
{
// it's full of logic!
}
}
Or even better:
public abstract class A
{
public virtual void Main() { }
}
public abstract class B : A
{
public override sealed void Main()
{
// it's full of logic!
}
}
This is really a concrete class; it's only abstract in so far as one can't instantiate it. For example, if I wanted to execute the logic in B.Main() I would have to first get an instance of B, which is impossible.
If inheritors don't actually have to provide implementation, then why call it abstract?
Put another way, why does C# allow an abstract class with only concrete members?
I should mention that I am already familiar with the intended functionality of abstract types and members.
Perhaps a good example is a common base class that provides shared properties and perhaps other members for derived classes, but does not represent a concrete object. For example:
public abstract class Pet
{
public string Name{get;set;}
}
public class Dog : Pet
{
public void Bark(){ ... }
}
All pets have names, but a pet itself is an abstract concept. An instance of a pet must be a dog or some other kind of animal.
The difference here is that instead of providing a method that should be overridden by implementors, the base class declares that all pets are composed of at least a Name property.
The idea is to force the implementor to derive from the class as it is intended to provide only a basis for a presumably more specialized implementation. So the base class, while not having any abstract members may only contain core methods an properties that can be used as a basis for extension.
For example:
public abstract class FourLeggedAnimal
{
public void Walk()
{
// most 4 legged animals walk the same (silly example, but it works)
}
public void Chew()
{
}
}
public class Dog : FourLeggedAnimal
{
public void Bark()
{
}
}
public class Cat : FourLeggedAnimal
{
public void Purr()
{
}
}
I think a slightly more accurate representation of your question would be: Why does C# allow an abstract class with only concrete members?
The answer: There's no good reason not to. Perhaps someone out there has some organizational structure where they like to have a noninstantiatable class at the top, even if a class below it just inherits and adds nothing. There's no good reason not to support that.
You said it -- because you can't instantiate it; it is meant to be a template only.
It is not "really a concrete class" if you declare it as abstract. That is available to you as a design choice.
That design choice may have to do with creating entities that are (at risk of mixing the terminology) abstractions of real-world objects, and with readability. You may want to declare parameters of type Car, but don't want objects to be declarable as Car -- you want every object of type Car to be instantiated as a Truck, Sedan, Coupe, or Roadster. The fact that Car doesn't require inheritors to add implementation does not detract from its value as an abstract version of its inheritors that cannot itself be instantiated.
Abstract means providing an abstraction of behaviour. For example Vehicle is an abstract form. It doesn't have any real world instance, but we can say that Vehicle has accelerating behaviour. More specifically Ford Ikon is a vehicle, and Yamaha FZ is a vehicle. Both these have accelerating behaviour.
If you now make this in the class form. Vehicle is abstract class with Acceleration method. While you may/ may not provide any abstract method. But the business need is that Vehicle should not be instantiated. Hence you make it abstract. The other two classes - Ikon and FZ are concrete classes deriving from Vehicle class. These two will have their own properties and behaviours.
With regards to usage, using abstract on a class declaration but having no abstract members is the same as having the class public but using protected on its constructors. Both force the class to be derived in order for it to be instantiated.
However, as far as self-documenting code goes, by marking the class abstract it informs others that this class is never meant to be instantiated on its own, even if it has no virtual or abstract members. Whereas protecting the constructors makes no such assertion.
The compiler does not prevent implementation-logic, but in your case I would simply omit abstract ?! BTW some methods could be implemented with { throw Exception("must inherit"); } and the compiler could not distinguish fully implemented classes and functions including only throw.
Here's a potential reason:
Layer Supertype
It's not uncommon for all the objects
in a layer to have methods you don't
want to have duplicated throughout the
system. You can move all of this
behavior into a common Layer
Supertype.
-- Martin Fowler
There's no reason to prevent having only concrete methods in an abstract class - it's just less common. The Layer Supertype is a case where this might make sense.
I see abstract classes serving two main purposes:
An incomplete class that must be specialized to provide some concrete service. Here, abstract members would be optional. The class would provide some services that the child classes can use and could define abstract members that it uses to provide its service, like in the Template Method Pattern. This type of abstract class is meant to create an inheritance hierarchy.
A class that only provides static utility methods. In this case, abstract members don't make sense at all. C# supports this notion with static classes, they are implicitly abstract and sealed. This can also be achieved with a sealed class with a private constructor.

C# - How to create constructor for inherited class where parent class only has static constructor

For example, say I wanted to create a class that inherits System.Diagnostics.StopWatch, and for this example pretend that System.Diagnostics.Stopwatch.StartNew() is the only public constructor for that class (I know its not, but I'm trying to inherit a different class where that is the case) :
public class Example : System.Diagnostics.Stopwatch
{
public Example()
{
// ... return System.Diagnostics.Stopwatch.StartNew();
}
}
I know there are obvious workarounds, but just wondering if this is possible in C#
There are basically three scenarios where you can't inherit from a class:
The intended parent class is declared as sealed, which prohibits inheriting from it.
The intended parent class doesn't have an accessible constructor.
The intended parent class is a static class.
If you are in one of these 3 scenarios, you will not be able to inherit from that class, plain and simple, don't look for a usable workaround because there isn't.

Base class implementing interface

What are the cons/risks of base class implementing an interface?
Is it better to always implement an interface on the sub-class?
When would you use one or the other?
public interface IFriendly
{
string GetFriendly();
}
public abstract class Person: IFriendly
{
public abstract string GetFriendly();
}
VS.
public interface IFriendly
{
string GetFriendly();
}
public abstract class Person
{
// some other stuff i would like subclasses to have
}
public abstract class Employee : Person, IFriendly
{
public string GetFriendly()
{
return "friendly";
}
}
Well, you need to think of it that way:
public interface IBreathing
{
void Breathe();
}
//because every human breathe
public abstract class Human : IBreathing
{
abstract void Breathe();
}
public interface IVillain
{
void FightHumanity();
}
public interface IHero
{
void SaveHumanity();
}
//not every human is a villain
public class HumanVillain : Human, IVillain
{
void Breathe() {}
void FightHumanity() {}
}
//but not every is a hero either
public class HumanHero : Human, IHero
{
void Breathe() {}
void SaveHumanity() {}
}
The point is that you base class should implement interface (or inherit but only expose its definition as abstract) only if every other class that derives from it should also implement that interface.
So, with basic example provided above, you'd make Human implement IBreathing only if every Human breaths (which is correct here).
But! You can't make Human implement both IVillain and IHero because that would make us unable to distinguish later on if it's one or another. Actually, such implementation would imply that every Human is both a villain and hero at once.
To wrap up answers to your question:
What are the cons/risks of base class implementing an interface?
None, if every class deriving from it should implement that interface too.
Is it better to always implement an interface on the sub-class?
If every class deriving from base one should also implement that interface, it's rather a must
When would you use one or the other?
If every class deriving from base one should implement such interface, make base class inherit it. If not, make concrete class implement such interface.
Starting with a base class ties you to the implementation of the base class. We always start off thinking the base class is exactly what we want. Then we need a new inherited class and it doesn't quite fit, so we find ourselves going back and modifying the base class to fit the needs of the inherited class. It happens all the time.
If you start with an interface then you have a little more flexibility. Instead of having to modify the base class you can just write a new class that implements the interface. You can have the benefit of class inheritance when it works, but you're not tied to it when it doesn't work.
I loved class inheritance when I first started with OOP. What's surprising is how infrequently it ends up being practical. That's where the principal of Composition Over Inheritance comes in. It's preferable to build functionality out of combinations of classes rather than having it nested inside inherited classes.
There's also the Open/Closed principle. If you can inherit, great, but you don't want to have to go back and change the base class (and risk breaking other stuff) because it's needed for a new inherited class to work right. Programming to an interface instead of a base class can protect you from having to modify existing base classes.

Trouble with Interfaces, Inheritance, and Polymorphism

I have come to a point in my program where my polymorphism is broken. I realize that this is in my code, and I understand why; I'm just not sure how best to resolve it.
I have three model classes which have the same interface, but very significantly different implementations. I created an interface, and then three independent classes, which also derive from a ModelBase class:
public interface IMyModel
{ ... }
public class MyModelA : ModelBase, IMyModels
{ ... }
public class MyModelB : ModelBase, IMyModels
{ ... }
public class MyModelC : ModelBase, IMyModels
{ ... }
So far fine and dandy.
I have a ViewModel base class, which takes a model as a constructor:
public abstract class MyViewModelBase
{
public MyViewModelBase(ModelBase Model)
this.model = Model;
}
Now where I am caught; I want to have a concrete ViewModel class that can accept any of the three Model classes above:
public class MyViewModel : MyViewModelBase
{
MyViewModel(IMyModel Model) : base (Model) // <- Invalid Polymorphism!
{
// More here
}
}
This doesn't work, because it is possible for an implementation of IMyModel to not be based on ModelBase. The argument cannot be safely passed to the base constructor.
I can see one solution being to create an abstract base class derived from ModelBase for these models with exception-throwing content, and using that as the type in my ViewModel. I had started with a base class, but found that almost every part had some difference! However, that seems like a lot of work. Also, it won't ensure that derived classes implement everything (like an interface does). Finally, it seems to devalue the interface concept (indeed, I wouldn't need one anymore).
I don't see any way of marking the interface as saying that derived classes must have a specific base class. It would be nice if I could do this, but it's not allowed:
public interface IMyModel : MyModelBase
{ ... }
Is there a better way to do this?
Clarification:
I probably oversimplified the names here. I have other Models and ViewModels using the base classes, but not implementing the interface.
public class MyOtherModel : ModelBase // But not IMyModel!
{ ... }
public class MyOtherViewModel : MyViewModelBase
{
MyOtherViewModel(MyOtherModel Model) : base(Model) // This works
{ ... }
}
You could make your base class implement the interface, then inherit your implementation classes from the base class, marking the base class and methods as abstract (MustInherit/MustOverride in VB parlance). This would give you your polymorphism and guarantee the interface.
you could use generic constraints:
public class MyViewModel<T> : MyViewModelBase where T : IMyModel , ModelBase
{
MyViewModel(T model) : base (model) // T inherits ModelBase and implements IMyModel , so it is legal
{
// More here
}
}
Often (not always) when you find yourself building an Abstract Base Class it means you are trying to share both an interface and some common logic. Perhaps you can split these two things?
Move the common interface into IMyModels, and extract the common functionality into a separate class. Then include an instance of that helper class in each model. Essentially use composition to share functionality instead of inheritance.
Make ModelBase implement IMyModel. If ModelBase does not implement all methods of the interface, implement them as abstract methods.
To my understanding
Models are stupid Data containers
Interfaces describe behaviour and Functionality, not data.
So why bother putting interfaces on the models at all?
#Yochai : Good point, using Generics - saves code, but you must first declare base classes (only one per class, there's no mixed inheritance in C#), then any amount of interfaces, thus your code should be:
public class MyViewModel<T> : MyViewModelBase where T : ModelBase, IMyModel

Cannot create an instance of the abstract class or interface

I'm not familiar on using abstract class.
I'm trying to call a abstract class and get this error Cannot create an instance of the abstract class or interface and I already research this error but I'm really confused on this.
Here's my code:
string B1String;
while ((B1String = OasisFile.ReadLine()) != null)
{
Questions_Base oQuestions_Base = new Questions_Base(); // error here
oQuestions_Base.Import(B1String);
}
Please advice me.. thanks!
The purpose of an abstract class it to serve as part of a class hierarchy where more-derived classes share some common implementation.
If you have a flight simulator, you might define an abstract class ThingsThatFly that implements some properties (air speed, altitude, heading) and methods (TakeOff(), Land()) that all flying things have in common, but would be declared abstract because ThingsThatFly is an abstraction of all concrete things that fly. You could certainly have classes inbetween as well, for example Cessna172 could inherit from Airplane that inherits from ThingsThatFly. You would do that if all airplanes have some common implementation that e.g. birds don't have (for example, a Fuel Remaining property).
You would then have a number of concrete (= real life) things that fly like a Cessna 172, a Space Shuttle and a Duck. Each of those would be a concrete class that derives from ThingsThatFly
This is different than having the concrete classes implement an interface such as IThingsThatFly in that the abstract class provides not only a definition of the properties and methods that are expected, but also provides a (hopefully useful) implementation of those properties and methods.
An Abstract class can only be inherited.
public class CustomClass : Questions_Base {
}
Here's a link all about abstract classes and how to use them.
You cant create an instance of an abstract class.
You need to define a concrete class that inherits the abstract class, and create an instance of that.
Abstract class is made to be overriden by Derived class. If you have to have Abstract class, first create s Derived class from it and use Derived class contructor.
If it's not important, just remove abstract word from Questions_Base class declaration, so making that non abstract one. Also because in code provided I don't see any abstract member, so may this one is correct choice.
Regards.
An abstract class cannot be instantiated. You must provide an implementation for the class.
abstract class Animal
{
public abstract void Speak() { }
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Woof");
}
}
See MSDN on abstract for more information
From the documentation: "The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class."
The purpose of using abstract is exactly to prevent instantiation, because you only created the class to use as a base class and never want an instance created.
More here.
An abstract class is one which MUST be inherited.
It falls somewhere between an Interface, which defines only the interface that a class must implement and no implementation code and a class that you can create an instance of which defines both the interface and the implementation code. There are several abstract classes in the .NET framework such as CollectionBase. You cannot create an instance of CollectionBase, it is intended for you to create a class that inherits from it and extends it's capabilities.
You should simpley be able to remove the kwy work "abstract" from your class definition of Questions_Base or create a new class definition that inherits from it.
Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy. What's special about them, is that you can't create an instance of them - if you try, you will get a compile error. Instead, you have to subclass them, as taught in the chapter on inheritance, and create an instance of your subclass. So when do you need an abstract class? It really depends on what you do. To be honest, you can go a long way without needing an abstract class, but they are great for specific things, like frameworks, which is why you will find quite a bit of abstract classes within the .NET framework it self. A good rule of thumb is that the name actually makes really good sense - abstract classes are very often, if not always, used to describe something abstract, something that is more of a concept than a real thing.

Categories