Cleaven
Cleaven

Reputation: 974

How to write private variable string in console

I need to declare a private variable that should not be available to any derived classes, outside classes or programs.

So I did this but I don't know if it's correct to start off with:

class Program
{
    public const int width = 100;
    public const int height = 30;
    protected int gameCharX;
    protected int gameCharY;
    private string clea = "C";
    static void Main(string[] args)
    {
        Console.WriteLine("" + clea);
        Console.SetWindowSize(width, height);              
        Console.ReadLine();
    }        
}

It also gives me the error in the writeline:

Error 1 An object reference is required for the non-static field, method, or property

I'm not sure what to do.

Upvotes: 0

Views: 1336

Answers (1)

Hameed Syed
Hameed Syed

Reputation: 4275

The error is because your variable clea is not accessible in main. Why not accessible? Because it's (Program) not a static class where you can access class properties(clea) without instantiation. Hence, you can create an instance on the go like below

  Console.WriteLine("" + new Program(). clea);

Or

Make the private method as static

`private static string clea = "C"`;

And access it as usual

Console.WriteLine("" + clea);

Upvotes: 2

Related Questions