I am writing an abstract base class. I want all the classes that inherit from it to inherit a constructor that basically does the same things for all the classes. Is this possible?
Doing your constructor protected will do the stuff
public abstract class A
{
protected A(string v) { V = v; }
public string V { get; protected set; }
}
public class AA : A
{
public AA(string v) : base (v) {}
}
If the abstract base class has a default constructor (i.e. a constructor with no parameters), it will automatically be called by the derived classes constructors, unless they explicitly call another constructor of the base class.
abstract class B
{
protected B()
{
...
}
protected B(object foo)
{
...
}
}
class D : B
{
public D()
: base() // not actually necessary, since it's called implicitly
{
}
public D(object foo)
: base(foo)
{
}
}
In your derived classes constructor, you will need to call your base constructor like so:
base(param1,param2,...)
If you do not call the base constructor explicitly, the default constructor in the base class will be called, if one exists. If not, you will get a compile error.
Related
I have a question regards chaining constructors I read some question on StackOverflow and some c# articles but I cannot understand the topic fully. So I have a BaseClass that is inherited by DerivedClass. In the DerivedClass, I have no argument constructor but it's calling the base constructor using: base() and it also passing a value. Is this the primary purpose of the base keyword used in the constructor to pass a value to the inherited class from the derived one or is something more out there. And also in the derived class, we have a second constructor that takes 1 parameter and its using: this(). I can't understand why when I remove: this() from this constructor "VS" tells me "There is no argument given that corresponds to the required formal parameter "i" of BaseClass.BaseClass(int) ? Why I can't just have one argument constructor in the DerivedClass without using this()?
public class BaseClass
{
protected int _Num;
public BaseClass(int i)
{
_Num = i;
}
public int Num { get => this._Num ; set => _Num = value; }
}
public class DerivedClassA : BaseClass
{
private string _Name;
private int _AnotherValue;
public string Name { get => this._Name ; set => this._Name = value; }
public int AnotherValue { get => this._AnotherValue; set => this._AnotherValue = value; }
public DerivedClassA() : base(123)
{
_Name = "testing";
}
public DerivedClassA(int param2) : this() <-- Why i can't compile the program without the this() keyword here ?
{
AnotherValue = param2;
}
}
public class Program
{
public static void Main(string[] args)
{
DerivedClassA objA = new DerivedClassA(5);
}
}
I can't find a duplicate that exactly matches, so I'll provide an answer.
Imagine these classes:
public class Base
{
public Base()
{
}
}
public class Derived : Base
{
public Derived()
{
}
}
Try it online
When you initialize a derived class, you have to first initialize the base. In our example above, the Base class has a parameterless constructor, so the derived class can implicitly call it. If we add a base second constructor, this logic remains true, and the parameterless constructor will still be implicitly called:
public class Base
{
public Base()
{
}
public Base(int a)
{
}
}
public class Derived : Base
{
public Derived()
{
}
}
Try it online
But if we take away the parameterless constructor, Derived must now call the base constructor explicitly:
public class Base
{
public Base(int a)
{
}
}
public class Derived : Base
{
public Derived() : base(1)
{
}
}
Try it online
So what happens if we add an extra derived class constructor? Well, that also has to call the base class (either directly, or indirectly):
public class Base
{
public Base(int a)
{
// this method body is executed first
}
}
public class DerivedA : Base
{
public DerivedA(string name, int val) : base(val)
{
// this method body is executed second (last if you used this constructor, e.g. new DerivedA("hello", 1) )
}
public DerivedA() : this("test", 5) // this will call the constructor above, which will first call base. So the final chain is: base, constructor above, this constructor
{
// this method body is executed third (last if you used this constructor, e.g. new DerivedA() )
}
}
public class DerivedB : Base
{
public DerivedB(string name, int val) : base(val)
{
}
public DerivedB() : base(5) // this will call the base constructor, and then this constructor. The constructor above will not be used.
{
}
}
Try it online
Note that all classes have a parameterless constructor when no other constructor is defined, so the following two examples are equivalent:
public class BaseA
{
}
public class BaseB
{
public BaseB()
{
}
}
You'll note that SharpLab shows the compiler removed the empty constructor from BaseB() since it's superfluous.
Finally, a derived class without an explicitly defined constructor, will still call the base class constructor implicitly:
public class Base
{
public Base()
{
// this method body is executed first
Console.WriteLine("Base constructor");
}
}
public class Derived : Base
{
}
Try it online
So to summarise: unless your base class has a parameterless constructor, your derived class constructors have to either call a base constructor directly, or indirectly through another derived class constructor. Obviously you only need to call a single base constructor method, as with any other class instantiation. You don't need matching derived methods for each base method, so long as you can construct the base with the values you do have.
I have a generic type G<T> where T : A, where A is an abstract class. In each class B derived from A I want to have a field of type G<B>, without writing repetetive code, however I'm not sure if it's even possible. One way to do this would be
abstract class A
{
protected object g;
protected abstract void SetG();
public A()
{
SetG();
}
}
class B : A
{
protected override void SetG()
{
this.g = new G<B>();
}
public B() : base() {}
}
But this would mean a lot of repetetive code in every derived class. Is there a better way to do this?
You could add an extra abstract class in between:
public abstract class A<T> : A where T : A
{
protected override void SetG()
{
this.g = new G<T>();
}
}
...then, update your B declaration to:
public class B : A<B>
{
public B() : base() { }
}
I believe that what you are trying to do is a Covariant Conversion. See this MSDN article on using delegates and see if that works for you. Look in the section "Using Delegates with Covariant Type Parameters".
In your A:, create a delegate:
Func<G<A>> GetG;
Then, in your derived classes, set this func pointer to a function of type
Func<G<B>>
Bingo!
I have a Base class with a template. Within this class there is an abstract method with a return type of the type in the template (see below).
I wish to create a new class , Derived , which inherits from this Base class , which (as expected) must "override" that method.
My question is how do I declare and implement the Derived class and the "overridden" method ?
Thanks allot in advance,
Guy.
public abstract class Base<MyType>
{
protected abstract MyType Foo();
}
public class Derived : Base ?????
{
protected override MyType Foo() ?????
{
return new MyType();
}
}
Simply specify the actual type for the generic base class, i.e something like:
public class Derived : Base<MyType>
{
protected override MyType Foo()
{
// some implementation that returns an instance of type MyType
}
}
Where MyType is the actual type you want to specify.
The other option would be to keep the derived class as generic, so something like:
public class Derived<T> : Base<T>
{
protected override T Foo()
{
// some implementation that returns an instance of type T
}
}
You must specify concrete type for Base or make Derived also generic:
public class Derived : Base<int>
{
protected override int Foo();
{
return 0;
}
}
or generic version:
public class Derived<TMyType> : Base<TMyType>
{
protected override TMyType Foo();
{
return default(TMyType);
}
}
Declare it in the same way:
public class Derived<MyType> : Base<MyType>
{
protected override MyType Foo()
{
return new MyType();
}
}
I have a set of classes where my base has a constructor that takes a configuration object and handles transferring the values to its properties.
abstract class A { public A(ObjType MyObj){} }
abstract class B : A {}
class C : A {}
class D : B {}
class E : B {}
Is it possible to implicitly call a non-default base constructor from child classes or would I need to explicitly implement the signature up the chain to do it via constructors?
abstract class A { public A(ObjType MyObj){} }
abstract class B : A { public A(ObjType MyObj) : base(MyObj){} }
class C : A { public A(ObjType MyObj) : base(MyObj){} }
class D : B { public A(ObjType MyObj) : base(MyObj){} }
class E : B { public A(ObjType MyObj) : base(MyObj){} }
If that is the case, is it better to just implement a method in the base then have my factory immediately call the method after creating the object?
Implicitly? No, constructors are not inherited. Your class may explicitly call it's parent's constructor. But if you want your class to have the same constructor signatures as the parent class's, you must implement them.
For example:
public class A
{
public A(int someNumber)
{
}
}
// This will not compile becase A doesn't have a default constructor and B
// doesn't inherit A's constructors.
public class B : A
{
}
To make this work you'd have to explicitly declare the constructors you want B to have, and have them call A's constructors explicitly (unless A has a default constructor of course).
public class B : A
{
public B(int someNumber) : base(someNumber)
{
}
}
No it's not possible to call a non-default base constructor implicitly, you have to make it explicit.
You need to explicitly implement it up the chain. Also, importantly, in your original code, you will not be able to call a new B(), since A does not have a default constructor, and B does not call A's constructor that has an arg.
How and when to call the base class constructor in C#
You can call the base class constructor like this:
// Subclass constructor
public Subclass()
: base()
{
// do Subclass constructor stuff here...
}
You would call the base class if there is something that all child classes need to have setup. objects that need to be initialized, etc...
Hope this helps.
It's usually a good practice to call the base class constructor from your subclass constructor to ensure that the base class initializes itself before your subclass. You use the base keyword to call the base class constructor. Note that you can also call another constructor in your class using the this keyword.
Here's an example on how to do it:
public class BaseClass
{
private string something;
public BaseClass() : this("default value") // Call the BaseClass(string) ctor
{
}
public BaseClass(string something)
{
this.something = something;
}
// other ctors if needed
}
public class SubClass : BaseClass
{
public SubClass(string something) : base(something) // Call the base ctor with the arg
{
}
// other ctors if needed
}