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.

6 comments:

  1. Mannen ɗie tijdens hᥙn werk еen uniform dragen: zucht.

    ReplyDelete
  2. Wow, this paragraph is fastidious, my sister is analyzing such things,
    therefore I am going to tell her.

    ReplyDelete
  3. I'm extremely impressed along with your writing abilities and also with the structure in your weblog.

    Is that this a paid theme or did you customize it your self?

    Anyway stay up the nice high quality writing, it's rare to
    see a nice blog like this one nowadays..

    ReplyDelete
  4. Hi there all, here every one is sharing these kinds of know-how, so it's nice to read
    this weblog, and I used to visit this webpage every day.

    ReplyDelete
  5. Welkom bij uw vertrouwde online Fietsenwinkel.

    ReplyDelete
  6. Very good info. Lucky me I ran across your blog by chance (stumbleupon).
    I've saved it for later!

    ReplyDelete