Why is parent's constructor getting called? - c#

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

Related

How To Implicitly Call A Method From An Interface When An Object Is Initialized [duplicate]

This question already has answers here:
C# How to execute code after object construction (postconstruction)
(11 answers)
Closed 2 years ago.
I have an interface that I need to implement on a few winforms and I would like to be able to call a specific method when an object is initialized.
I know I can just explicitly call the method from the constructor of the class, but it would be very nice to be able to implicitly call this method on all classes that implement the interface.
Similar to Mixins in Pyhton.
I'm not sure if an interface is the way this should be done, or just simply inheriting from another class that calls the method in it's constructor, but every class will have it's own implementation of the method so the latter might not work.
Desired result:
interface AutoRun{
void CodeToRun();
}
class Foo: AutoRun {
void CodeToRun(){
Console.WriteLine("The Code Was Ran");
}
}
class Bar: AutoRun {
void CodeToRun(){
Console.WriteLine("This Other Code Was Ran");
}
}
Foo f = new Foo(); // -> "The Code Was Ran"
Bar b = new Bar(); // -> "This Other Code Was Ran"
You could use a base class. The constructor chain will always execute for every class in the inheritance chain implicitly. For method calls, it's not completely implicit, but calling base.CodeToRun() will get you whatever base implementation is in there. You can even avoid the base.CodeToRun() call if you decide you don't want it to run.
public interface IAutoRun
{
public void CodeToRun();
}
public abstract class AutoRun : IAutoRun
{
public AutoRun()
{
Console.WriteLine("Base constructor run");
}
public virtual void CodeToRun()
{
Console.WriteLine("The code was run");
}
}
public class Foo : AutoRun
{
public Foo()
{
Console.WriteLine("Derived constructor run");
}
public override void CodeToRun()
{
Console.WriteLine("Running my derived method code");
base.CodeToRun();
}
}
An interface is just a contract. So, you cannot make it run anything. But you can always put code that must be run at object creation into a constructor.
A constructor cannot be specified in an interface. But you can call a method implementing the interface in a constructor.
If you want it to happen automatically, use an abstract base class which implements this interface and calls the code to be run in its constructor. An abstract class cannot be instantiated, and abstract members must be overridden in the deriving (non abstract) classes. In a deriving class the autorun method will then run "magically" without an explicit method call.
The naming conventions in .NET tell us to start Interface names with an upper case "I".
interface IAutoRun
{
void CodeToRun();
}
abstract class AutoRunBase : IAutoRun
{
public AutoRunBase()
{
CodeToRun();
}
public abstract void CodeToRun();
}
Now let us implement a concrete class with an auto run functionality:
class Foo : AutoRunBase
{
public override void CodeToRun()
{
Console.WriteLine("Hello World");
}
}
Note that the AutoRunBase class (I use to append "Base" to abstract classes to mark them as such) calls the not yet implemented CodeToRun method in its constructor. Since you cannot call new on an abstract class, this is not a problem, because it will be overridden in the deriving classes.
The constructor of a base class is automatically called before the constructor of the derived class (in this case Foo has an implicitly declared default constructor).
var run = new Foo(); // Prints "Hello World" to the console.
The interface is not required to make this work, but it allows to separate the contract form the implementation.
If you do not use the interface, you can also declare CodeToRun as protected instead of public and thus disallow it to be called from outside.

Factory pattern: Restrict object construction to factory

I have a class T and a factory TFactory that creates objects of type T.
I want to make sure that only the factory is allowed to create new T objects.
A halfhearted solution would be to require the factory as a parameter in T's constructor, for the only purpose that only somebody who at least brings a factory object can create T's:
class T
{
public T(TFactory Tf)
{
if (!(Tf is TFactory))
throw new InvalidOperationException("No factory provided");
}
}
But wherever a TFactory is at hand, one could construct T's.
Another approach would be to check via stack tracing, if the constructor call really came from within a TFactory, but this seems overkill to me.
A third apporach would be to put both T and TFactory in an assembly of their own, ad make T's constructor internal. But a new project and assembly just for this purpose?
Any better idea anybody?
(Although my code is C#, this is probably a more general question)
Here's something very similar to your third approach: declare the factory as a inner class of T, and make T's constructor private:
public class T {
public class Factory {
public T GetT() {
return new T(); // simple implementation just for an example here
}
}
private T() {}
}
Since Factory is inside T, it can access the private constructor, but outside code cannot. If you don't want to create a separate assembly, you could consider this approach.
Note that you could still put the factory class and T in two different files, with partial classes:
public partial class T {
private T() {}
// other stuff about T here...
}
// in another file
public partial class T {
public class Factory {
public T GetT() {
return new T();
}
// other stuff about Factory here...
}
}
public abstract class T { }
public class TFactory
{
public T CreateT() => new TImpl();
private class TImpl : T { }
}
The second approach is the worst one. That behavior is absolutely unobvious and unclear to a client. Stack tracing also slows down execution. The 1st and the 2nd make sense.
If you want to have total control of instance creation put it into the type. Use a factory method. Remember, one should be reasonable when putting constraint on instance creation. E.g. the instance should be initiated with a polymorphal (virtual) method. One can't call such a method from a constructor (a very bad practice), so the method should be called after construction. For not to put that responsibility on the client, hide the constructor from one and provide a factory method.
abstract class Base
{
protected abstract void Initialize();
}
class Derived : Base
{
protected Derived() { /* ... */}
protected override void Initialize() { /* ... */}
public Derived CreateDerived()
{
var derived = new Derived();
derived.Initialize();
return derived;
}
}

Derived class explicit base constructor call

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) { }
}

Abstract class constructor in C#

In c# we can't create an obeject of a abstact class or interface it means abstract class do not have any constructor, is it true ?
or if it have then what is it's purpose there?
As others have said, abstract classes usually have constructors (either explicitly or the default one created by the compiler) - and any derived class constructor will have to chain through the abstract class's constructor in the normal way. That's the important bit... suppose you have an abstract class which stores the name associated with an instance - because you always want a name, and you don't want to write the Name property in each concrete derived class. You might provide a constructor which takes that name and assigns it to a field... and then every subclass constructor would have to go through that constructor, so that you still knew you'd always have a name. If you want to know more about constructor chaining, read my article on it.
Here's an example of that:
public abstract class DemoBase
{
private readonly string name;
public string Name { get { return name; } }
protected DemoBase(string name)
{
this.name = name;
}
// Abstract members here, probably
}
public class FixedNameDemo : DemoBase
{
public FixedNameDemo()
: base ("Always the same name")
{
}
// Other stuff here
}
public class VariableNameDemo : DemoBase
{
public VariableNameDemo(string name)
: base(name)
{
}
// Other stuff here
}
To further answer your comment on BoltClock's answer, asbtract classes can't have private abstract methods, but they can have private constructors. Indeed, it's sometimes useful to have only private constructors in an abstract class, because it means the class can only be derived from within the program text of the same class. This allows you to create pseudo-enums:
public abstract class ArithmeticOperator
{
public static readonly ArithmeticOperator Plus = new PlusOperator();
public static readonly ArithmeticOperator Minus = new MinusOperator();
public abstract int Apply(int x, int y);
private ArithmeticOperator() {}
private class PlusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x + y;
}
}
private class MinusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x - y;
}
}
}
In this respect, an abstract private method/property could make sense - it could be accessed by the base class but provided by the derived classes within the same class's program text. However, it's prohibited by the specification. Usually, protected abstract members would solve the same problem - but not quite always.
Good question. Here's why Abstract classes need constructors even though they cannot be instantited.
In any Object oriented language like C#, object construction is an hierarchical process. Look at the code below. When you instantiate any object of type DerivedClass, it must construct the base object first before creating the object of typeof DerivedClass. Here the base class may or may not be an Abstract class. But even when you instantiate an object of a concrete type derived from an abstract class it will still need to call the constructor of the Base class before the object of DerivedClass type is created, hence you always need a constructor for Abstract class. If you have not added any constructor, C# compiler will automatically add a public parameterless constructor to the class in the generated MSIL.
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass constructor called..");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("DerivedClass constructor called..");
}
}
DerivedClass obj = new DerivedClass();
//Output
//BaseClass constructor called..
//DerivedClass constructor called..
PS: Assuming, If Abstract base classes
are not allowed to have constructors
because they need not be instantiated,
the whole fundamentals of the object
oriented programming will go on toss.
The idea behind Abstract types are to
represent objects that have some
features and behaviours but not
complete as whole to allow independant
existence.
No. it means that operator new is not allowed to create object from this type of class.
The purpose might be that are allocated/initialized some properties of class.
abstract usually leave some methods to implement.
Regarding the interface, this structure holds only the signatures of method, delegates or events. That may be implemented in class that use interface. You cant create a object.
Read about new
EDIT:
What is the purpose of constructor in abstract class ?
When one class inherit another class, the parent class of it had to be created first while object is crated. In class do not implement some special constructor always is used default one [className()]. When you override some method then the implementation of functionality is taken form class which override the method. This is why method used in constructor should never be virtual. Same logic for abstract class, such class can have a lot of functionality, and only one method that should be implemented by child class.
Abstract classes have constructors but you can't call them directly as you can't directly instantiate abstract classes.
To answer your comment, the concept of a private abstract method or property makes no sense, because private prevents anybody else from accessing it, and abstract prevents itself from accessing it. So there would essentially be no possible way to call it.
EDIT: see Jon Skeet's answer on private constructors. Private members of other kinds cannot exist in abstract classes, though.
Abstract classes do have constructors. When you create an instance of a derived class, its parent class' constructors are called. This applies to classes derived from abstract classes as well.

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