CodeMonkey1313
CodeMonkey1313

Reputation: 16011

Public Properties and Private Members C#

What are the benefits of only using public properties instead of using the public property to access a private variable?

For example

public int iMyInt { get; set; }

instead of

private int myint;
public int iMyInt { get { return myint; } set { myint = value; } }

Other than letting .NET manage the variable / memory underneath the property, what are the advantages (or disadvantages for that matter)?

Upvotes: 3

Views: 1692

Answers (6)

Amit
Amit

Reputation: 670

Just a quick note: Automatically implemented properties must define both get and set accessors.

Upvotes: 0

Randolpho
Randolpho

Reputation: 56381

My personal preference is for automatic properties unless otherwise necessary.

The advantage of using automatic properties is, of course, succinctness. It takes less room, it's easier to read, it's easier to type.

The disadvantage is that you no longer have access to the private backing variable, and sometimes you need that.

So: when you need to use the private backing variable, use the "old" method. When you don't, use an automatic property. Never use a public field. That's just crazy-talk.

Upvotes: 1

Richard
Richard

Reputation: 1169

I'd suggest that more important than requiring less typing is the increased readability of your code. I would generally advise using automatic properties as my default option, and only switching to explicit properties if there is a particular requirement for them.

Upvotes: 8

Reed Copsey
Reed Copsey

Reputation: 564323

The two will be nearly identical once compiled to IL.

My rule of thumb, personally, is to use automatic properties. They are more concise, and require less typing, and I know that, when I use them, they're meant to just be a simple wrapper with no logic.

If I later need to add logic, it's easy to switch to my own backing field, and there are no (external) consequences.

Upvotes: 4

Bob
Bob

Reputation: 99674

There is no difference one way or the other until you want something to happen when a property is got or set.

For instance, if you want a OnMyIntSet event, you could not use the automatic property syntax.

Upvotes: 1

Michael
Michael

Reputation: 55395

Using automatic properties (the first example) requires less typing.

It is highly recommended to have only public properties and not public fields. Many properties are simple wrappers around private fields. Automatic properties save you the time and hassle of manually creating the property and backing field.

The actual code behind automatic and manual properties for the simple case you mentioned should be nearly identical.

Upvotes: 11

Related Questions