Artichoker

Hello,

I am developing a console text game. Here is the problematic code for it.

Code Snippet

using System;

namespace CoolGameTextClean
{
class Engine
{
private static Player MainCharacter = new Player();

public Engine()
{
MainCharacter.StartingLevel();
}

public static void Main()
{
Console.WriteLine(MainCharacter.DisplayLevel.ToString()); // Displays 0. It should display 1
Console.ReadLine();
}
}
}


Code Snippet

namespace CoolGameTextClean
{
class Player
{
private int Level;

public int DisplayLevel
{
get
{
return Level;
}
set
{
Level = value;
}
}

public void StartingLevel()
{
Level = 1;
}

}

}


The problem is, in the Main method, I want to display the Level of the MainCharacter. In the constructer, I call the StartingLevel method, which sets the Level to 1, however, when I run the program, it displays the level as 0. What am I doing wrong Can someone tell me

Thanks.


Re: Visual C# General Problem showing int from another class

Bruno_1

The engine constructor is never called, no engine object is instantiated. When you run the program, only the static main will be called. So on the main you should place "MainCharacter.StartingLevel();" first

Hope this helped





Re: Visual C# General Problem showing int from another class

Artichoker

Hi, thanks for posting.

If the engine constructer is never called, how do I call it




Re: Visual C# General Problem showing int from another class

Bruno_1

Since Engine is not static, then you should instantiate it, like you did with the Player class.
Engine engine = new Engine();
The issue here is that MainCharacter is static, so it is available on the class level, you could set it as instance field (and set it public, or expose it through a public propertylike when you did with level and DisplayLevel property), and then on the main you'll have something like:

Engine engine = new Engine();
Console.WriteLine(engine.MainCharacter.DisplayLevel.ToString()); // It will display 1
Console.ReadLine();

Or you can make the engine class itself static, and replace the constructor with a static constructor :
static Engine()
{
MainCharacter.StartingLevel();
}

Hope this helped





Re: Visual C# General Problem showing int from another class

Artichoker

Thanks. That helped a lot. I've got it fixed now.