C # inheritance

I am new to inheritance and wanted to ask something. I have a base class that has many functions that are shared by several derived classes.

The only difference for each derived class is the only method called Name. The functionality is the same for each derived class, but there is a need for distinguishing names.

I have a property in the base class Name. How to organize this so that derived classes can override the property of the base class?

Thanks.

+4
source share
7 answers

Declare your method as virtual

 public class A { public virtual string Name(string name) { return name; } } public class B : A { public override string Name(string name) { return base.Name(name); // calling A method } } public class C : A { public override string Name(string name) { return "1+1"; } } 
+4
source

Use the virtual property:

 class Base { public virtual string Foo { get; set; } } class Derived : Base { public override string Foo { get { // Return something else... } set { // Do something else... } } } 
+3
source

You can declare it using a virtual or abstract keyword in the base class, then the derived class can overload it

+3
source

you need to declare your property (in the base class) as virtual

+2
source

For each derived class to override a property, you just need to mark the property as virtual

 class Base { public virtual Property1 { get { ... } set { ... } } } 
+2
source

Well, I'm not sure about your description that inheritance is actually the correct solution to the problem, but here's how you can override a property:

 class Base { public virtual string Name { get; set; } } 

But do you need it to be writable? The readonly property may make more sense, in which case it might work:

 class Base { public virtual string Name { get { return "BaseName"; } } } class Derived : Base { public override string Name { get { return "Derived"; } } } 
+2
source

In the base class:

 public virtual string Name { get; set; } 

In derived classes:

 public override string Name { get; set; } 

However, if the only difference between the classes is that they have different names, I would say that instead of inheriting you should just use the base class with the name specified in the constructor:

eg.

 public class MyObject { public string Name { get; private set; } public enum ObjectType { TypeA, TypeB, ... } public MyObject(ObjectType obType) { switch (obType) { case ObjectType.TypeA: Name = "Type A"; // and so on } } } 
+2
source

All Articles