1

My project(C# mvc) classes inherit one base class, for some reason I need to create constructor on base class having parameters like bellow:

Public class MyBase
{
 Public MyBase(string param1, string param2, string param3)
{
}
}

Public class MyClass : MyBase
{
}

Now problem is that, on each derived class need to defined base class constructor with parameter.If I not defined base class constructor in derived class then show me error” parameter less constructor ” it is painfull to write code on each class for base class constructor,is there any way to avoid this work

shamim
  • 6,640
  • 20
  • 85
  • 151

2 Answers2

1

The only way to get rid of the error it to add a parameter less constructor, however that obviously isn't ideal because you you need to specify parameters.

In Visual Studio 2015 you can click on the error and click "Generate Constructor", which makes the process of adding the constructors much easier.

See this answer for a bit of an explanation behind this.

You do have to redeclare constructors, because they're effectively not inherited. It makes sense if you think of constructors as being a bit like static methods in some respects.

Community
  • 1
  • 1
Cyral
  • 13,999
  • 6
  • 50
  • 90
0

If I got you right, you want a class that derives from the base you have but you don't want to override base constructor. Here is one solution you might like. What if you hide construction of your class?

public class MyBase
{

    public MyBase(string param1, string param2, string param3)
    {
    }
}

public class MyClass: MyBase
{
    // notice - hide constructor - private
    private MyClass(string p1, string p2, string p3) : base(p1, p2, p3)
    {

    }

    public static MyClass Create()
    {
        return new MyClass(null, null, null);
    }
}

usage

var c = MyClass.Create();

As result, your callers don't have to worry about using constructor. More over, you can now completely change construction of the derived class

T.S.
  • 18,195
  • 11
  • 58
  • 78
  • T.S thanks for your reply, your solution is very interesting. But i requirement is different,Let's describe i dont want to do anything in my derived class,with out any touch or inherit or any charm what i dont know may solve my problem.Hope you understand my desired.i am more than 100 class it's really pain for me to change or put one line on each.Thank for your reply – shamim Dec 31 '15 at 04:00