Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# compilation error when attempting to assign instance variables from base class in derived class

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading