Getters, setters, and properties best practices. Java vs. C# Getters, setters, and properties best practices. Java vs. C# java java

Getters, setters, and properties best practices. Java vs. C#


Pre-C# 6

I'd use the last of these, for a trivial property. Note that I'd call this a public property as both the getters and setters are public.

Immutability is a bit of a pain with automatically implemented properties - you can't write an auto-property which only has a getter; the closest you can come is:

public string Foo { get; private set; }

which isn't really immutable... just immutable outside your class. So you may wish to use a real read-only property instead:

private readonly string foo;public string Foo { get { return foo; } }

You definitely don't want to write getName() and setName(). In some cases it makes sense to write Get/Set methods rather than using properties, particularly if they could be expensive and you wish to emphasize that. However, you'd want to follow the .NET naming convention of PascalCase for methods, and you wouldn't want a trivial property like this to be implemented with normal methods anyway - a property is much more idiomatic here.

C# 6

Hooray, we finally have proper read-only automatically implemented properties:

// This can only be assigned to within the constructorpublic string Foo { get; }

Likewise for read-only properties which do need to do some work, you can use member-bodied properties:

public double Area => height * width;


If all you need is a variable to store some data:

public string Name { get; set; }

Want to make it appear read-only?

public string Name { get; private set; }

Or even better...

private readonly string _name;...public string Name { get { return _name; } }

Want to do some value checking before assigning the property?

public string Name {   get { return m_name; }   set   {      if (value == null)         throw new ArgumentNullException("value");      m_name = value;   }}

In general, the GetXyz() and SetXyz() are only used in certain cases, and you just have to use your gut on when it feels right. In general, I would say that I expect most get/set properties to not contain a lot of logic and have very few, if any, unexpected side effects. If reading a property value requires invoking a service or getting input from a user in order to build the object that I'm requesting, then I would wrap it into a method, and call it something like BuildXyz(), rather than GetXyz().


Use properties in C#, not get/set methods. They are there for your convenience and it is idiomatic.

As for your two C# examples, one is simply syntactic sugar for the other. Use the auto property if all you need is a simple wrapper around an instance variable, use the full version when you need to add logic in the getter and/or setter.