Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract constructor in C# [duplicate]

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); } 
like image 210
AndreyAkinshin Avatar asked Feb 19 '10 19:02

AndreyAkinshin


People also ask

What is an abstract constructor?

A constructor is a method called when a class is instantiated, and an abstract class cannot be instantiated. It sounds counterintuitive, right? In this article, we'll see why abstract classes can have constructors and how using them provides benefits in subclasses instantiation.

What is the use of abstract constructor?

Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor.

Can we abstract constructor?

yes it is. And a constructor of abstract class is called when an instance of a inherited class is created.

Can constructor be abstract in C#?

Yes, an abstract class can have a constructor, even though an abstract class cannot be instantiated.


1 Answers

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")      {         ...      } } 
like image 197
tvanfosson Avatar answered Sep 26 '22 07:09

tvanfosson