puretppc
puretppc

Reputation: 3292

Parent class does not contain a constructor that takes 0 arguments

My Game class takes two arguments, but for some reason this code I wrote won't work:

class Game
{
    string consoleName;
    int gameID;

    public Game(string name, int id)
    {
        this.consoleName = name;
        this.gameID = id;
    }
}

Here is my child class.

class RolePlayingGame : Game
{
    int level;
}

Upvotes: 2

Views: 254

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172408

Try this:

class RolePlayingGame : Game {
    public RolePlayingGame(string name, int id) : base(name, id){
        //Code here
    }
    int level;
}

As noted by Tim S in comments, C# automatically creates something like a public RolePlayingGame() : base() { }. Since Game does not have a parameterless constructor, this fails. So you need to create a parameterized constructor. You have to explicitly define the constructors in the sub classes.

Upvotes: 3

King King
King King

Reputation: 63317

class RolePlayingGame : Game {
  public RolePlayingGame(string name, int id) : base(name, id){
    //...
  }
  int level;
}

Or provide a parameterless constructor for your base class:

class Game
{
   public Game(){ //You don't even need any code in this dummy constructor         
   }
   //....
}

NOTE: Note that if you understand a parameterless constructor is OK, you can use it (as provided in the second approach).

Upvotes: 6

Related Questions