0

I have used two ways for setting up a public class in C# (and VB.NET)

Option 1 - Setters & Getters

public class foo
{
  private string _bar;
  public string bar
  {
    get { return _bar; }
    set { _bar = value; }
  }
}

Option 2 - Simple Public Class

Public Class foo
    Public string bar = "";   
End Class

I've done it both ways, but it's much simpler and less code with Option 2 - and I don't see the difference in terms of other coding to set or get values for the class or performance - both ways work just fine.

My question is "Why would you do Option 1 if there are not some other 'special things' happening in the getter or setter? And if so - what would those reasons potentially be?

What I want to know if there's some 'Convincing Argument' for using setters and getters for this and if so 'Specifically Why?

Cheers, Charlez

Charlez
  • 871
  • 3
  • 11
  • 17

1 Answers1

3

For your specific situation, its faster just to have a public variable (all getters and setters are turned into functions at compile time).

Unlike Java, which if you have getter/setter functions they MUST be called as functions. If at some point you want to change your public variable to a getter/setter the code base doesn't have to change (BUT IT MUST STILL BE RECOMPILED) This means if you are developing a library, and you want to hot swap the DLL and you change a public variable to a getter/setter it will break the target program.

ohmusama
  • 4,159
  • 5
  • 24
  • 44