Public Fields Versus Automatic Properties

Public Fields versus Automatic Properties

In a related question I had some time ago, there was a link to a posting on Jeff's blog, explaining some differences.

Properties vs. Public Variables

  • Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
  • You can't databind against a variable.
  • Changing a variable to a property is a breaking change. For example:

    TryGetTitle(out book.Title); // requires a variable

C# autoproperty vs normal fields

AFAIK they behave exactly the same.

No they don't.

  • Fields can't be used in data binding (at least in some binding implementations)
  • You can add more logic later for properties without breaking source or binary compatibility
  • Properties can't be passed by reference
  • You can't add an initializer to an automatically implemented property
  • They'll clearly be different in terms of reflection
  • Philosophically, properties are logically part of the API whereas fields are an implementation detail

in c# you can always rewrite Foo into this: [...]

Well you can if you don't care about binary or source compatibility, yes. In some cases that's really not an issue - in other cases it's very, very much an issue. Why not make the choice to expose your API rather than your implementation details from the start? It's not like adding { get; set; } in your code is adding much clutter...

For more ranting, see my article on this.

Difference between Automatic Properties and public field in C# 3.0

Because they are implemented differently in the resulting IL code (and machine language). An Automatic property is still exposed as a public getter and setter, whereas a public field is just that - a single field..

Thus, implementing an auto property allows you at some later date to change the internal behavior of either the getter or setter (like adding a validator) without recompiling or re=coding any dependant classes that use it...

What is the difference between properties and fields?

This one is just a field, which is what you call a variable that is declared directly on a class or struct:

public string Name;

This one is a property:

public string Name { get; set; } 

They are functionally similar. The getter and setter allow you to customize what happens when the variable is accessed or set, respectively. Traditionally, a property is used to expose a private field that is used inside the class to do work. You do this to expose the variable without allowing people to reach in and change or break the inner workings of the class.

This is part of Encapsulation.

In this particular syntax you are "auto-implementing" the getter and setter, which creates a hidden backing field that you never see anywhere in your code. The result is that working with this will seem extremely similar to just using a field.

Why not just use a field in this case? Aside from leading to better design, there are important implications that have more to do with convention. In a lot of cases where data binding is involved, for example, only properties are considered for binding. Fields are ignored. So in Entity Framework, a property might represent a column in a database... And it has to be a property. It cannot be a plain field.

The key lesson here is that if you want to expose a field outside you class, you should use a property to promote encapsulation and to signal to others (people and also code in some cases) that you really did intend to expose what you exposed.

More: What is the difference between a field and a property?

What is the advantage of using auto-implemented properties with the default access, instead of using public fields?

The main advantages are:

  1. Future-proofing your API - If you later need logic in the getter or setter, your public API doesn't change.
  2. Data binding - Most data binding frameworks only work against Properties, not Fields.

What is the difference between a field and a property?

Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.

public class MyClass
{
// this is a field. It is private to your class and stores the actual data.
private string _myField;

// this is a property. When accessed it uses the underlying field,
// but only exposes the contract, which will not be affected by the underlying field
public string MyProperty
{
get
{
return _myField;
}
set
{
_myField = value;
}
}

// This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
// used to generate a private field for you
public int AnotherProperty { get; set; }
}

@Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes.

@GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.

Why are public fields faster than properties?

Edit 2:

I had another potential thought here:

You mentioned that you are running on x64. I've tested this same issue on x86, and seen the same performance when using auto-properties vs. fields. However, if you look around on Connect and mailing list/forum posts, there are many references online to the fact that the x64 CLR's JIT is a different code base, and has very different performance characteristics to the x86 JIT. My guess is this is one place where x64 is still lagging behind.

Also, FYI, the struct/method/etc thing fixed in .net 3.5sp1 was on the x86 side, and was the fact that method calls that took structs as a parameter would never be inlined on x86 prior to .net3.5sp1. That's pretty much irrelevant to this discussion on your system.


Edit 3:

Another thing: As to why XNA is using fields. I actually was at the Game Fest where they announced XNA. Rico Mariani gave a talk where he brought up many of the same points that are on his blog. It seems the XNA folks had similar ideas when they developed some of the core objects. See:

http://blogs.msdn.com/ricom/archive/2006/09/07/745085.aspx

Particularly, check out point #2.


As for why automatic properties are better than public fields:

They allow you to change the implementation in v2 of your class, and add logic into the property get/set routines as needed, without changing your interface to your end users. This can have a profound effect on your ability to maintain your library and code over time.

---- From original post - but discovered this wasn't the issue--------

Were you running a release build outside of VS? That can be one explanation for why things aren't being optimized. Often, if you are running in VS, even an optimized release build, the VS host process disables many functions of the JIT. This can cause performance benchmarks to change.

Are there cases where Fields are better than auto-properties

From the question which you linked, the first answer https://stackoverflow.com/a/1180870/3419534 highlights one specific place where fields can be used and properties cannot, and that is as ref parameters.

Consider:

int a;
int B { get; set; }
void F()
{
a = 0;
G(ref a); // a will be incremented
B = 0;
G(ref B); // Compiler error CS0206
}
void G(ref int p)
{
++p;
}

Why are C# auto-implemented properties public?

You are correct that auto-implemented properties that simply expose a backing field are not much of a gain over a public field.

As Alan Kay said:

But most people who use setters simply use them to simulate direct assignments to interior variables, and this violates the spirit and intent of real OOP.

However, there is an advantage to an auto-implemented property over a public field, and that is that it's a non-breaking change to later revise the implementation. If you have a public field, and code outside your class manipulates that public field, you can't change it to a private field in a future version of the class, or else any other code that touches that field will have to be recompiled. By contrast, once you have a public property, you can revise the implementation of that property in a future version, and client classes can continue using it with zero changes.

So it's useful to use auto-implemented properties for properties that right now would have trivial getter and setter implementations, but that may have more complex implementations in the future.



Related Topics



Leave a reply



Submit