a blog for those who code

Monday, 23 June 2014

Class does not contain a constructor that takes 0 arguments

This error actually means that your class does not have any constructor which takes 0 arguments.Each and every class must have a contructor, so at first check that the constructor is present in your class or not. Note that if you do not create a constructor, a constructor will be created for you by the compiler.

That means your class.

class Shape { }

upon compilation will become

class Shape{
public Shape(){ }
}

Suppose if you have explicitly created a constructor which takes one argument, then compiler will not create an empty constructor for you. That means, if you have created your class something like

class Shape{
public Shape(int arg){ }
}

and if you create an object of this class as

Shape sh = new Shape();

It will throw you an exception as "Class does not contain a constructor that takes 0 arguments", because your class does not have any constructor which takes 0 argument, and you are creating an object and calling a constructor which takes 0 argument. Instead you have to explicitly call the parameterized constructor when creating the object.

Shape sh = new Shape(4)

Sometimes you may get an error like "Parent does not contain a constructor that takes 0 arguments". This error means you are calling a base class constructor which takes 0 arguments, but your base class doesn't have any constructor which takes 0 arguments. For example...

class Shape{
public Shape(int arg){ }
}

class Square : Shape{
public Square(int arg){ }
}

The above code will give you an error because it explicitly calls the parent constructor which takes 0 arguments. Instead of that you have to add an explicit call...

class Square : Shape{
public Square(int arg) : base(arg)
{ }
}

OR you have to add an parameterless parent constructor.

If you have any questions or suggestions, you are most welcomed. Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment