Why use fields instead of properties?

I am new to C # and I think this is a wonderful thing. So wonderful that I don't see the real benefits of using fields. Even for private fields, it seems that the flexibility and modularity that offers offer will at best save you from serious headaches and in the worst case will have no effect.

The only advantage I can see for fields is that you can initialize them inline. But in most cases you want to initialize them in the constructor. If you are not using inline initialization, is there any reason not to use properties all the time?

Edit: some people explain the need to back up properties using fields (explicitly or automatically). Let me clarify my question: is there a reason to use fields other than fallback properties? Ie, is there ever SomeType someField; preferably SomeType SomeProperty { get; set; } SomeType SomeProperty { get; set; } SomeType SomeProperty { get; set; } ?

Edit 2: DanM, Skurmedel and Seth all gave really helpful answers. I took DanM as it is the most complete, but if someone had to summarize their answers to one answer, I would be happy to accept it.

+27
c # coding-style properties field
Jan 30 '10 at 1:28
source share
13 answers

Typically, properties require a support field, unless they are "getter / setter" automatic properties.

So, if you just do ...

 public string Name { get; set; } // automatic property 

... you do not need a field, and I agree, there is no reason to have it.

However, if you do ...

 public string Name { get { return _name; } set { if (value = _name) return; _name = value; OnPropertyChange("Name"); } } 

... you will need this _name field.

For private variables that do not require any special get / set logic, this is really the decision whether to make a private automatic property or just a field. I usually make a field, then if I need it to be protected or public , I will change it to an automatic property.

Update

As Yasir noted, if you use automatic properties, the field still hidden behind the curtains is still not just what you really need to type. So, on the bottom line: properties do not store data, they provide access to data. Fields are what actually store the data. Therefore, you need them, even if you do not see them.

Update 2

Regarding your revised question ...

is there some time SomeType someField; preferably SomeType SomeProperty { get; set; } SomeType SomeProperty { get; set; } SomeType SomeProperty { get; set; } ?

... one thing that comes to mind: if you have a private field and (according to the agreement for private fields), you call it _name , which signals you and everyone who reads your code that you work directly with private data. If, on the other hand, you make the whole property and (according to the convention for the properties) call your private property Name , now you can’t just look at the variable and say that it is private data. Thus, using only properties removes some information. I have not tried working with all the properties to evaluate if this is important information, but something is definitely lost.

One more thing, more insignificant, is that public string Name { get; set; } public string Name { get; set; } public string Name { get; set; } requires more typing (and a little messier) than private string _name .

+21
Jan 30 '10 at 1:32
source share

Properties are a wonderful thing, but overhead is associated with access to resources. Not necessarily a problem, but something to be aware of.

Prevent Overuse of Getters and Setters Properties

Most people do not realize that the properties of getters and seters are similar to methods when it comes to overhead; this is basically the syntax that sets them apart. The compiler does not bind a non-intelligent getter or setter that does not contain instructions other than accessing the field, but in many other cases this is not possible. You should carefully consider your use of properties; from within the class, access fields directly (if possible) and never blindly call properties again without storing the value in a variable. All that is said does not mean that you should use public fields!

Source: http://dotnet.sys-con.com/node/46342

+11
Jan 30
source share

If you want to have something readonly , you should pretty much use a field, as there is no way to specify an automatic property to create a read-only field.

I do this quite often.

A simplified example:

 class Rectangle { private readonly int _width; private readonly int _height; public Rectangle(int width, int height) { _width = width; _height = height; } public int Width { get { return _width; } } public int Height { get { return _height; } } } 

This means that inside the Rectangle nothing can change the width or height after building. If someone tries, the compiler will complain.

If I used an automatic property with a private setter, the compiler would not protect me from myself.

Another reason I see is that if some of the data should not be exposed (stay private ), why is it a property?

+9
Jan 30
source share

Try using the property when using ref / out args:

 someObject.SomeMethod(ref otherObject.SomeProperty); 

It will not compile.

+9
Apr 01 '10 at 13:18
source share

I do not understand why you are using private auto-programs. What an advantage exists

 private int Count {get; set;} 

over

 private int count 
+4
Jan 30 '10 at 1:48
source share

There is no reason to publish fields.

If you publicly open a field, you cannot change the source of information, from the built-in definition to the configuration file without refactoring. \

You can use the field to hide internal data. I rarely use this, I only use fields when I do something to hide in public and use it in the property. (i.e. I do not use automatic property generation)

+3
Jan 30 '10 at 1:32
source share

Fields are the only place where you can save state. Properties are just a couple of methods with special syntax that allows you to map them to the get or set method, depending on how they are used: if the property changes or gets access to the state, this state should still be stored in the field.

You do not always see the fields. With C # 3 automatic properties, the field is created for you by the compiler. But he is still there. In addition, automatic properties have some significant limitations (for example, support for INotifyPropertyChanged, lack of business logic in setters), which means that they are often unacceptable, and you still need to create an explicit field and a manually defined property.

According to David's answer , you are right if you are talking about the API: you almost never want the internal state (of the field) to be part of the API.

+3
Jan 30 '10 at 1:35
source share

The syntax for fields is much faster to write than for properties, so when it is safe to use a field (private to the class), why not use it and save unnecessary input? If the automatically implemented properties had a nice short concise syntax and you had to do extra work to create a plain old field, people could just start using the properties. In addition, this convention is now in C #. This is how people think, and this is what they expect to see in the code. If you do something else in the usual way, you will confuse everyone.

But you might ask why the syntax for the fields does not create an automatically implemented property instead of the field, so you get the best of both worlds - properties everywhere and a short syntax.

There is a very simple reason why we still need to have explicit fields:

C # 1.0 did not have all of these nice features that we have now, so the fields were a fact of life - you could not live without them. Lots and lots of code rely on fields and properties, which are different things. Now it is simply impossible to change without breaking tons of code.

I also suspect that there are performance implications, but perhaps this can be resolved by jitter.

So, we are stuck with the fields forever, and since they are there and they took the best syntax, it makes sense to use them when it's safe.

+3
Jan 30
source share

Although I agree with what I perceive as “intention” in a statement by David Basarab: “There is no reason to publicly disclose the fields,” I would like to add a slightly different emphasis:

I would change the quote from David above to read: "There is no reason to publicly disclose fields ... outside the class ... except for the conscious choice of encapsulating fields in properties through which access is strictly controlled.

Properties are not just syntax “veneers” over fields, “tied to” C #: they are the main language function developed for valid reasons, including:

  • control over what is exposed and not exposed to external classes (encapsulation, data hiding)

  • allows you to perform certain actions when accessing or setting a property: actions that are best expressed in the "get" and "set" properties, and not "promoted" to external methods.

  • Design interfaces cannot define fields: but they can define properties.

Good OO Design means creating a conscious choice of “state”:

  • local variable fields: which state is private for the method and the transition process: local variables are usually valid only within the scope of the method or even with a "narrow service life", as within the scope of something like a 'loop'. Of course, you can consider the parameter variables in the method as "local".

  • class instance fields: which state is private to the class and has an independent existence for each instance of the class, but most likely it should be used in several places in the class.

  • instance static fields: which state will be a property of only the class, regardless of the number of instances of the class.

  • the state consciously and consciously reveals the "outside" class: the key idea is that between the class and the "consumers" of the data provided by the class, there is at least one level of indirection. The “reflecting side” of the “exposition” is, of course, the conscious intention to hide (encapsulate, isolate) the implementation code.

    but. through public properties: all aspects of this are well covered in all other answers here.

    b. through indexers

    from. using methods

    e. Public static variables are commonly found in utility classes, which are often static classes.

Invite you to check out MSDN on 'Fields ... MSDN by Properties ... MSDN on Indexers

+3
Jan 30
source share

Fields and properties are not interchangeable. I assume that you say this is access to private fields through private properties. I do this when it makes sense, but for the most part it is not necessary. In any case, the JIT optimizer will use private field access through private property in most cases. And closing a private field in a private property is not considered a change, since private members are not part of your interface.

Personally, I will never disclose the fields of a protected / public instance. It is generally acceptable, however, to open a public static field with readonly modifier if the field type itself is immutable. This is often observed with staticStart.Empty static fields.

+2
Jan 30
source share

As others have noted, in any case, you will need a personal support field for the properties.

There is also an advantage in using fields over properties. In 99.99% of cases, this does not matter. But in some it may be.

+2
Jan 30 '10 at 1:35
source share

Speed. If a field is set or read billions of times during the simulation, you want to use the field, not the property, to avoid the overhead of the subroutine. According to OO (DDD?), As far as possible, in these cases, I would recommend using fields only in a class designed to represent a kind of “value” like a person. Logic should be kept to a minimum. Rather, you have a person or owner.

But if you have these problems, you probably are not programming C ++, not C #, right?

0
Jan 30 '10 at 2:45
source share

There are some good (partial) answers from @Seth (fields work better, so in a private context you can use it to your advantage when it makes sense), @Skurmedel (fields can be read-only), @Jenk (fields can be used for ref / out). But I would like to add one more thing:

You can use simplified initialization syntax to set the value of a field, but not a property. i.e:.

 private int x = 7; 

against

 private int x { get; set; } // This must go in the constructor, sometimes forcing you to create // a constructor that has no other purpose. x = 7; 
0
Mar 12 '15 at 13:53 on
source share



All Articles