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

Time:07-04

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?

CodePudding user response:

You need to make your assignments in the constructor of the derived classes.

class Cruiser: Ship
{
    public Cruiser() {
       type = 'C';
       lives = 2;
    }
}

CodePudding user response:

What am I doing wrong here

Your syntax is not valid C#, as the error says you cannot set a variable in the body of a class

what is the correct way to achieve this

Firstly, dont just declare public fields. Use encapsulated properties and then have a constructor that passes these values from the derived class. Also, the convention in c# is public properties are PascalCase

class Ship
{
    public char Type {get;}
    public int Lives {get;}

    public Ship(char type, int lives)
    {
        this.Type = type;
        this.Lives = lives;
    }
}

class Cruiser: Ship
{
    public Cruiser() : base('C',2) {}
}

class Destroyer: Ship
{
    public Destroyer() : base('D',2) {}
}
  • Related