The following gives me an error in C#:
using System;
class Ship
{
public char type;
public int lives;
}
class Cruiser: Ship
{
type = 'C';
lives = 2;
}
class Destroyer: Ship
{
type = 'D';
lives = 2;
}
class Program
{
static void Main(string[] args)
{
Ship[,] field = new Ship[2,2];
Cruiser c = new Cruiser();
Destroyer d = new Destroyer();
field[0,0] = c;
field[1,0] = c;
field[0,1] = d;
field[1,1] = d;
field[1,1].lives--;
Console.WriteLine(field[0,1].lives);
}
}
I get the following:
test.cs(11,10): error CS1519: Invalid token ‘=’ in class, record, struct, or interface m member declaration
test.cs(12,11): error CS1519: Invalid token ‘=’ in class, record, struct, or interface member declaration
test.cs(18,10): error CS1519: Invalid token ‘=’ in class, record, struct, or interface member declaration
test.cs(19,11): error CS1519: Invalid token ‘=’ in class, record, struct, or interface member declaration
I do not understand why this occurs as I have defined the instance variables already in my base class. I was under the impression I could simply refer to them in the derived class and assign new values to them.
What am I doing wrong here and what is the correct way to achieve this?
>Solution :
You need to make your assignments in the constructor of the derived classes.
class Cruiser: Ship
{
public Cruiser() {
type = 'C';
lives = 2;
}
}