Derived class explicit base constructor call - c#

I am trying to learn C#. The below data is from a Microsoft C# help website.
I don't understand this statement, "If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor by using base."
I thought that if there is no default constructor for a class, C# will automatically assign default values to int, char or whatever is declared in a class. If a base class does not have a constructor and it has a child class, does the rule mentioned in the last sentence not apply? Please clarify.
In a derived class, if a base-class constructor is not called explicitly by using the base keyword, the default constructor, if there is one, is called implicitly. This means that the following constructor declarations are effectively the same:
C#
public Manager(int initialdata)
{
//Add further instructions here.
}
C#
public Manager(int initialdata)
: base()
{
//Add further instructions here.
}
If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor by using base.

If you do not define a constructor for a class:
public class DemoClass
{
public void SomeFunction() { }
}
C# will add a default (parameterless) constructor for you. In this case; nothing special needs to be done with derived classes, as they will use the provided default constructor. Of course, you can always define your own default (parameterless) constructor:
public class DemoClass
{
public void DemoClass() { }
public void SomeFunction() { }
}
Which still doesn't require anything special for derived classes, since they can still use it. If however, you define a parameterized constructor, without defining a default:
public class DemoClass
{
public void DemoClass(string argument) { }
public void SomeFunction() { }
}
Now there is no default (parameterless) constructor for derived classes to use; and you need to say which constructor to use with base:
public class DerivedClass : DemoClass
{
public DerivedClass() : base(String.Empty) { }
}

Related

Empty constructor in inheriting class C#

I have written a simple generic class in C#.
class Foo<T>
{
public object O{get;set;}
public Foo(object o)
{
O=o;
}
}
and another class inheriting from it
class Bar:Foo<object>
{
public Foo(object o):base(o)
{ }
}
My question is whether I can avoid writing that constructor in Bar class, because it does nothing special at all. PS: the parameter in constructor is necessary.
No, you can't. There's no inheritance of constructors. The constructor in Bar does do something: it provides an argument to the base constructor, using its own parameter for that argument. There's no way of doing that automatically.
The only constructor the compiler will supply for you automatically is one of equivalent to:
public Bar() : base()
{
}
for a concrete class, or for an abstract class:
protected Bar() : base()
{
}
... and that's only provided if you don't supply any other constructors explicitly.

Why is parent's constructor getting called?

I have an asbtract class Example. Another generic class UsesExample uses it as a constraint, with a new() constraint. Later, I create a child to Example class, ExampleChild, and use it with generic class. But somehow when the code in generic class tries to create new copy, it invokes not the constructor in the child class, but the constructor in the parent class. Why does it happen?
Here's the code:
abstract class Example {
public Example() {
throw new NotImplementedException ("You must implement it in the subclass!");
}
}
class ExampleChild : Example {
public ExampleChild() {
// here's the code that I want to be invoken
}
}
class UsesExample<T> where T : Example, new() {
public doStuff() {
new T();
}
}
class MainClass {
public static void Main(string[] args) {
UsesExample<ExampleChild> worker = new UsesExample<ExampleChild>();
worker.doStuff();
}
}
When you crate an object, all constructors are called. At first the base class constructor constructs the object so that the base members are initialized. Later the others constructors in hierarchy are called.
This initialization may call static functions so that it makes sense to call the constructor of an abstract base class event if it has no data members.
Whenever you create a new instance of a derived class, the base class's constructor is called implicitly. In your code,
public ExampleChild() {
// here's the code that I want to be invoked
}
is really turned into:
public ExampleChild() : base() {
// here's the code that I want to be invoked
}
by the compiler.
You can read more on Jon Skeet's detailed blog post on C# constructors.
In a derived class, if a base-class constructor is not called explicitly using the base keyword, then the default constructor, if there is one, is called implicitly.
from msdn
also, you can read here

Is it good to have a constructor in abstract class?

Is it good to have a constructor in abstract class?
is it a good programming practice to create constructor of abstract class? since abstract classes can not be initialized, their child classes are initialized.
Following is my class structure.
public abstract class Scheduler
{
private Storyboard timer;
protected Scheduler()
{
// initialize the timer here.
timer = new Storyboard();
this.PollInterval = 60;
}
}
public class TaskScheduler : Scheduler
{
public TaskScheduler()
: base()
{
}
}
Yes, it's absolutely fine. Just because the constructor can only be called by derived classes doesn't mean it won't be useful. For example, you might have an abstract class which represents a named entity of some kind - it would make sense to take the name as a constructor parameter.
It would probably be worth making the constructor protected, to make it even more obvious that you can't just call it from elsewhere.
Note that there being a constructor (or multiple constructors) in an abstract class does force derived class constructors to go through it, but it doesn't force the derived classes to have the same constructor signatures. For example:
public abstract class NamedFoo
{
private readonly string name;
public string Name { get { return name; } }
protected NamedFoo(string name)
{
this.name = name;
}
}
public class DerivedFooWithConstantName
{
public DerivedFooWithConstantName() : base("constant name")
{
}
}
In this case the derived class constructor is "removing" a parameter (by providing a constant value as the argument to the abstract class constructor) but in other cases it could "add" parameters that it required, or have a mixture.
There is absolutely no reason not to have a constructor in an abstract base class.
The abstract class is initialized and works just like any other class. The abstract keywords only do the following:
It prevents the class itself to be instantiated directly. It can only be instantiated by instantiating an inherited class. This does not change the behavior of initialization compared to a not abstract base class;
It allows you to have abstract methods, properties and events in the class.
If you e.g. do not have abstract methods, properties or events, exactly the same result can be accomplished by making the constructor of a class protected (like you did). This also prevents the class to be instantiated directly. The behavior does not change however compared to an abstract class.
The primary difference then becomes the ability to declare methods, properties and events as abstract which you can only do when the class is marked abstract.
Having constructor in abstract class can be useful at times. This question is a duplicate, and dealt great deal in an related post. Even though it specifically reference JAVA, conceptually it applies to C# also.
Can an abstract class have a constructor?
Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed. CA1012: Abstract types should not have constructors
Fix the violation by changing the accessibility of the constructor from public to protected.
Example:
namespace Sample
{
public abstract class Book
{
protected Book()
{
}
}
}

Getting the default constructor of a generic abstract class

I have a generic abstract base class from which I would like to derive from a dynamic type built through reflection.emit. Also I need to customize the derived class default constructor to initialize some fields. To build the default constructor of the derived class correctly I need to obtain the default constructor of the base class and invoke it. The problem is that I'm not being able to get the default constructor from the base class.
An example:
public abstract class Test<T>
{
private T data;
public abstract void Go();
}
public class TestDerive : Test<int>
{
public override void Go()
{
}
}
class Program
{
static void Main(string[] args)
{
ConstructorInfo[] constructors = typeof(Test<>).GetConstructors();
int length = constructors.Length;
}
}
I've tried everything and length is always zero. I don't understand. I've inspected similar cases in the reflector and there's indeed a call to the base constructor of the abstract class. The question is how do I get it to do the same ?
The default constructor of an abstract class is protected - you need to specify binding flags to access it via reflection. You can use
typeof(Test<>).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)
(It makes no practical difference whether it's public or protected in normal code, of course, as you can't call the constructor other than from a derived type.)
Note that this is the case whether or not the class is generic - it's the abstractness that's causing you problems.

Abstract constructor in C# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why can’t I create an abstract constructor on an abstract C# class?
Why I can't declare abstract an constructor of my class like this:
public abstract class MyClass {
public abstract MyClass(int param);
}
Constructors are only applicable to the class in which they are defined, that is, they are not inherited. Base class constructors are used (you have to call one of them, even if only calling the default one automatically) but not overridden by deriving classes. You can define a constructor on an abstract base class -- it can't be used directly, but can be invoked by deriving classes. What you can't do is force a derived class to implement a specific constructor signature.
It is perfectly reasonable to have a constructor defined, typically as protected, in order to define some common set up code for all derived classes. This is especially true, perhaps, when the abstract class provides some other default behavior which relies on this set up. For example:
public abstract class Foo
{
public string Name { get; private set; }
protected Foo( string name )
{
this.Name = name;
}
}
public class Bar : Foo
{
public Bar() : base("bar")
{
...
}
}
You can't declare it abstract, but you can have a constructor on your abstract class; just remove the word abstract and provide a body for it.
Constructors are closer to static methods rather than "regular" methods. Like static methods, they can be overloaded, but not overriden. That is, they are not inherited but can be redefined.
public BaseClass
{
public BaseClass( String s ) { ... }
public static void doIt ( String s ) { ... }
}
public SubClass extends BaseClass
{
public SubClass( String s ) { ... }
public static void doIt ( String s ) { ... }
}
public SubClass2 extends BaseClass
{
}
new SubClass( "hello" );
SubClass.doIt( "hello" );
new SubClass2( "hello" ); // NOK
SubClass2.doIt( "hello" ); // NOK
Constructors and static methods are never dispatched dynamically (virtually) -- You always know the concrete type you instantiate or the concrete class of the static method. That's why it makes no sense to have abstract constructor and abstract static method. That's why you can also not specify constructor and static method in interfaces.
You can even think of constructor as static factory method (and see the corresponding pattern):
MyClass obj = new MyClass(); // the way it is
MyClass obj = MyClass.new(); // think of it like this
The only case I see where it would make sense to define abstract constructor or abstract static method would be if reflection is used. In this case, you could ensure that all subclass would redefine the corresponding static method or constructor. But reflection is another topic...
Note: in languages such as Smalltalk where classes are regular objects, you can override static method and have abstract constructor. But it doesn't apply to Java because classes are not "regular" objects even if you can get them with reflection.
Abstract implies virtual. A non-default constructor can never be called polymorphically, so virtual and abstract are not allowed on constructors.
IF in a future version of C#, generics are enhanced to allow calling non-default constructors through a generic type parameter, then polymorphic calls to constructors would be possible and virtual and abstract constructors might be added as well.
What wrong with this:
public abstract class MyClass {
protected MyClass(int param)
{
}
}
In this case you oblige all derived classes to call base class constructor.
Because abstract constructors are not supported.
But a abstract class can have a constructor.
A constructor is not an ordinary method. It has a special purpose, and so is restricted to language features that make sense for that purpose. See also: Why do constructors not return values?
By definition, the class can't be instantiated directly, so in a sense, it already is abstract.

Categories