Daniel Kim
Daniel Kim

Reputation: 91

C# Public Variables - common programming practise

When I was in university 6-8 years ago, I learned that it was common practise to have public get and set methods but private variables when using Java. However these days, when I use C#, I realise that a lot of the common class variables have public accessibility, e.g. String.Length.

Is it common practise in C# to make variables public (so is it widely accepted that people can program in such a manner)?

Thanks

Upvotes: 2

Views: 238

Answers (3)

vincentp
vincentp

Reputation: 1433

You can also make a public variable readonly, instead of making its setter private:

class Foo
{
    public readonly int Bar; // Bar can only be initialized in the constructor

    public Foo()
    {
        this.Bar = 42;
    }
}

Upvotes: 0

lapadets
lapadets

Reputation: 1095

Often, it's also a good practice to mark the setter as private meaning that only the where your setter is declared can set the value for your property, and any other derived class can access it with the getter method. So there are a couple of ways to declare properties with:

Use the prop shortcut and hit Tab twice (Code Snippets in Visual Studio). This produces:

public int Foo{ get; set; }

Use the propg shortcut + Tab twice to declare the setter as private. Looks like this:

public int Foo{ get; private set; } 

Use the full implementation in using the shortcut propfull which will give you:

private int Foo;

public int MyProperty
{
    get { return Foo;}
    set { Foo = value;}
}

Upvotes: 1

vincentp
vincentp

Reputation: 1433

String.Length isn't really a public variable. In C#, it's common to use getters this way:

class Foo
{
    private int _bar;
    public int Bar
    {
        get { return _bar; } // getter
        set { _bar = value; } // setter
    }
}
// ...
Foo foo = new Foo();
foo.Bar = 42;

In other words, string.Length is only a getter for the read only variable string._lengh.

Upvotes: 2

Related Questions