Erin W.
Erin W.

Reputation: 51

How to assign different values of variables to different instances of the same object?

I'm trying to set up a very basic system that creates a Levels object via its constructor:

class Levels
{
    // private level properties
    private static string levelName { get; set; }
    private static int levelSize { get; set; }
    private static int levelNum { get; set; }

    // new level constructor. Takes name, size (to square) and level number.
    public Levels(string inName, int inSize, int inNum)
    {
        levelName = inName;
        levelSize = inSize;
        levelNum = inNum;                       
    }

    // ... GetLevel methods here...
}

and assigns those values to each particular instance of the object. However the output indicates to me that the levelName, levelSize and levelNum variables aren't "sticking" to each instance properly.

class Program
{
    static void Main(string[] args)
    {
        var Level1 = new Levels("Forest", 15, 1);
        var Level2 = new Levels("Desert", 22, 2);

        Console.WriteLine($"--- {Level1.GetLevelName()}, level {Level1.GetLevelNum()} ---");
        Console.WriteLine($"--- {Level2.GetLevelName()}, level {Level2.GetLevelNum()} ---");

        Console.ReadLine();
    }
}

// output:
//     --- Desert, level 2 ---
//     --- Desert, level 2 ---
// why is level 1 not displaying here?

I'm aware that if I were to move the constructor for level 2 after the first WriteLine command it would, hamfistedly, work, but obviously I need those values to stick to their instance.

Upvotes: 0

Views: 1516

Answers (2)

maccettura
maccettura

Reputation: 10818

The keyword static means that the variable is not instance level, but class level. Meaning your variables will be shared among all instances of your Levels class.

I would suggest rewriting it to:

public class Levels
{    
    public string LevelName { get; private set; }
    public int LevelSize { get; private set; }
    public int LevelNum { get; private set; }

    // new level constructor. Takes name, size (to square) and level number.
    public Levels(string inName, int inSize, int inNum)
    {
        LevelName = inName;
        LevelSize = inSize;
        LevelNum = inNum;                       
    }
}

Instead of your variables being private static, you will now use Properties that have a private setter (meaning they can only be set inside the class). Now each of your instances of Levels has their own respective values and nothing is shared between instances. This will also give you the added bonus of eliminating the need for your GetLevelName(), GetLevelNum(), etc methods too. You can now just say:

Console.WriteLine($"--- {Level1.LevelName}, level {Level1.LevelNum} ---");

I made a fiddle here to demo.

Upvotes: 7

MistyK
MistyK

Reputation: 6222

Remove static keyword from fields. Basically static keyword means that this field is the same for all instances of this class.

Upvotes: 2

Related Questions