2

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

Daniel Kim
  • 79
  • 9
  • 6
    That is a property, not public variable. See [`Properties in C#`](http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx). You see, that one thing why C# is better than Java. – Marcel N. Aug 25 '14 at 08:47
  • See: http://stackoverflow.com/questions/11874391/properties-vs-public-member-variables and http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c – Cody Gray - on strike Aug 25 '14 at 08:49
  • +1 comment. @MarcelN. As he said. The Private variables in C# can be set into access by means of Properties (which includes get, set accessors). By default Properties are public since we can access it outside the class. – Janani M Aug 25 '14 at 08:52

3 Answers3

2

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.

vincentp
  • 1,433
  • 9
  • 12
1

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;}
}
lapadets
  • 1,067
  • 10
  • 38
  • thanks guys for the response! Yeah, I didn't know that C# had such a thing like Properties. With C# seems like I can save a lot of time not needing to write full methods for get and set methods! – Daniel Kim Aug 25 '14 at 20:27
0

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;
    }
}
vincentp
  • 1,433
  • 9
  • 12