C# Properties and fields [duplicate] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language.
I am used to create my properties in C# using a private and a public field:
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
Now, with .NET 3.0, we got auto-properties:
public string Title { get; set; }
I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.
In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.
I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.
So, what am I missing here? Why would anyone actually want to use auto-properties?

We use them all the time in Stack Overflow.
You may also be interested in a discussion of Properties vs. Public Variables. IMHO that's really what this is a reaction to, and for that purpose, it's great.

Yes, it does just save code. It's miles easier to read when you have loads of them. They're quicker to write and easier to maintain. Saving code is always a good goal.
You can set different scopes:
public string PropertyName { get; private set; }
So that the property can only be changed inside the class. This isn't really immutable as you can still access the private setter through reflection.
As of C#6 you can also create true readonly properties - i.e. immutable properties that cannot be changed outside of the constructor:
public string PropertyName { get; }
public MyClass() { this.PropertyName = "whatever"; }
At compile time that will become:
readonly string pName;
public string PropertyName { get { return this.pName; } }
public MyClass() { this.pName = "whatever"; }
In immutable classes with a lot of members this saves a lot of excess code.

The three big downsides to using fields instead of properties are:
You can't databind to a field whereas you can to a property
If you start off using a field, you can't later (easily) change them to a property
There are some attributes that you can add to a property that you can't add to a field

I personally love auto-properties. What's wrong with saving the lines of code? If you want to do stuff in getters or setters, there's no problem to convert them to normal properties later on.
As you said you could use fields, and if you wanted to add logic to them later you'd convert them to properties. But this might present problems with any use of reflection (and possibly elsewhere?).
Also the properties allow you to set different access levels for the getter and setter which you can't do with a field.
I guess it's the same as the var keyword. A matter of personal preference.

From Bjarne Stroustrup, creator of C++:
I particularly dislike classes with a lot of get and set functions. That is often an indication that it shouldn't have been a class in the first place. It's just a data structure. And if it really is a data structure, make it a data structure.
And you know what? He's right. How often are you simply wrapping private fields in a get and set, without actually doing anything within the get/set, simply because it's the "object oriented" thing to do. This is Microsoft's solution to the problem; they're basically public fields that you can bind to.

One thing nobody seems to have mentioned is how auto-properties are unfortunately not useful for immutable objects (usually immutable structs). Because for that you really should do:
private readonly string title;
public string Title
{
get { return this.title; }
}
(where the field is initialized in the constructor via a passed parameter, and then is read only.)
So this has advantages over a simple get/private set autoproperty.

I always create properties instead of public fields because you can use properties in an interface definition, you can't use public fields in an interface definition.

Auto-properties are as much a black magic as anything else in C#. Once you think about it in terms of compiling down to IL rather than it being expanded to a normal C# property first it's a lot less black magic than a lot of other language constructs.

I use auto-properties all the time. Before C#3 I couldn't be bothered with all the typing and just used public variables instead.
The only thing I miss is being able to do this:
public string Name = "DefaultName";
You have to shift the defaults into your constructors with properties. tedious :-(

I think any construct that is intuitive AND reduces the lines of code is a big plus.
Those kinds of features are what makes languages like Ruby so powerful (that and dynamic features, which also help reduce excess code).
Ruby has had this all along as:
attr_accessor :my_property
attr_reader :my_getter
attr_writer :my_setter

The only problem I have with them is that they don't go far enough. The same release of the compiler that added automatic properties, added partial methods. Why they didnt put the two together is beyond me. A simple "partial On<PropertyName>Changed" would have made these things really really useful.

It's simple, it's short and if you want to create a real implementation inside the property's body somewhere down the line, it won't break your type's external interface.
As simple as that.

One thing to note here is that, to my understanding, this is just syntactic sugar on the C# 3.0 end, meaning that the IL generated by the compiler is the same. I agree about avoiding black magic, but all the same, fewer lines for the same thing is usually a good thing.

In my opinion, you should always use auto-properties instead of public fields. That said, here's a compromise:
Start off with an internal field using the naming convention you'd use for a property. When you first either
need access to the field from outside its assembly, or
need to attach logic to a getter/setter
Do this:
rename the field
make it private
add a public property
Your client code won't need to change.
Someday, though, your system will grow and you'll decompose it into separate assemblies and multiple solutions. When that happens, any exposed fields will come back to haunt you because, as Jeff mentioned, changing a public field to a public property is a breaking API change.

I use CodeRush, it's faster than auto-properties.
To do this:
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
Requires eight keystrokes total.

#Domenic : I don't get it.. can't you do this with auto-properties?:
public string Title { get; }
or
public string Title { get; private set; }
Is this what you are referring to?

My biggest gripe with auto-properties is that they are designed to save time but I often find I have to expand them into full blown properties later.
What VS2008 is missing is an Explode Auto-Property refactor.
The fact we have an encapsulate field refactor makes the way I work quicker to just use public fields.

Related

Why is it desirable to use all properties instead of public instance variables in c#?

I know properties have some advantages, but if you think you won't need a property, what's the harm in making it a public instance?
People say that changing the public field to a property will break code if you try to do it later on but in my experience changing it to a property breaks nothing.
I think that people mean that it breaks ABI (binary) compatibility, not the API (source) compatibility.
Although the syntax is identical, behind the scenes, access to properties and access to member variables are compiled differently.
That said, if your variable/property is not to be used from an assembly that you yourself do not compile, then there is no harm in changing it. But if it is part of a public interface, then it is better to make it a property, so that you will not regret it in the future.
It's about maintaining both binary and source compatibility. Some time in the future you may decide to make logic of assigning values more complex and to change fields to properties. This is where the problems emerge.
Public fields can be used as out and ref parameters. Properties cannot. This will produce uncompilable code.
Different Reflection methods are used to access fields and properties. That means any code that gets or sets values using Reflection will break, and you'll know about it only in run time.
Different IL operators are used to access fields and properties. That means cross-assembly compatibility is broken when fields are changed to properties and only one assembly is recompiled. This will make your program fail at run time.
I concour with you, if the property is just a wrapper on the field.
And the guys at Coding Horror looks like having our same opinion, I find very funny that frightened icon they use :)
http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html
A simple program.
Here I am adding two properties and one variables. We can use properties as per our decision. But I prefer to use properties because it helps to implement some bussiness validation and can hide the business logic form calling party.
class Program
{
static void Main(string[] args)
{
Human h = new Human();
h.FirstName = "Test";
h.LastName = "User";
Console.WriteLine(h.FullName);
Console.Read();
}
}
class Human
{
public string FullName { get { return FirstName + " " + LastName; } }
public string FirstName;//{ get; set; }
public string LastName;//{ get; set; }
}

Why do we use blank get; set; accessors in C#? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
c#: why have empty get set properties instead of using a public member variable?
string name;
vs
string name {get; set;}
Assuming your get and set are blank as above, what's the point in specifying them?
It encapsulates the compiler generated field, and provides you, the class or struct developer the ability to update it internally later without breaking your API by simply modifying the get/set part that you care about.
For instance, suddenly never want to return null? You can do that by simply changing the empty get to get { return storedName ?? ""; }. Of course, it means you suddenly need to manually control the variable, but that's a small price to pay for the flexibility.
The first use is an example of a field declaration. The second use is an example of an auto-implemented property.
It is generally bad practice to provide direct access to a field. However, the .NET team noticed that a lot of getters/setters are basically just that. For example, consider the following:
// C#
public string Name
{
get { return name; }
set { name = value; }
}
// Without properties (or a Java implementation)
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
Either way, that's a lot verbosity to really just expose a field. However, it is regularly the case that, as a developer, you need to go back and change how a field is handled internally, but you do not want to break or even affect other code if you can get away with it.
That is why using direct access to fields is bad. If you provide direct access to fields, but need to change something about using the field, then all code that uses that field must change as well. If you use a property (or even a method), then you can change the internal code and potentially not effect external code.
Consider the following example:
public string Name
{
get;
set;
}
Later you decide that you need to raise a changing and changed event around the setter. If you exposed a field, then it's time for a potentially big rewrite. If you used properties (or a method), then you can just add the logic there. You suddenly lose the benefit of auto-implementing properties, but you gained the ability to refactor your class without breaking existing code.
private string name;
public event NameChangingEventHandler NameChanging;
public event NameChangedEventHandler NameChanged;
public string Name
{
get { return name; }
set
{
OnNameChanging(/*...*/);
name = value;
OnNameChanged(/*...*/);
}
}
protected virtual void OnNameChanging(/*...*/) { }
protected virtual void OnNameChanged(/*...*/) { }
All of that maintains your public API and requires no work from users of the class (the rest of your code, or external developers using of your API). Breaking changes are not always avoidable, but avoiding direct access to fields is a good step to try to ensure that it won't happen. Auto-implemented properties are a quick, and easy way to do it.
(Unrelated: lost power while typing this and I am very happy that my browser saved most of it!)
The first one is actually a Field, but the second one is an Auto-Implemented property. The difference between them has already been discussed.
The first, assuming it's declared in class scope, is a field name. It's accessed as a field. The second is a property. A Blank get/set is known as an auto-property.
You might need to actually do something in your accessors in the future. Changing a field (which is what your first declaration is) to a property is a breaking change, so specifying accessors in advance is a small investment in the future.
Being able to add logic to a field's accessors without breaking compatibility is the standard explanation, and it's certainly a big one if you're writing a library or an application that's split among several assemblies that might be updated independently. I think it's something that one could dismiss as less of a concern if you're working on any sort of "all-in-one" software, though, since it'll all be recompiled anyway.
But even then, there's still another very compelling reason to only expose properties in your public interfaces: Even if you never need to make any internal updates, using fields can still lead to other problems on down the line because many portions of the .NET framework strongly prefer properties to fields. WPF, for example, does not generally support binding to fields. You can get around that by doing fancy things like implementing ICustomTypeDescriptor, but it's just so much easier to simply type {get; set;}.
string name {get; set;}
This is called auto implemented property. Actually, C# creates variable starting with _ itself, so on get, that variable value is fetched and on set, that variable value is set. Its just like normal properties. Where as string name; is just a field.
The first is a variable, the second is a (shorthanded) property
Properties are very nice, but as a general rule, objects shouldn't expose state to the public; they should be a black box from the perspective of outsiders. And you especially shouldn't state to direct change. State should change as a side effect of asking the object instance to do something useful in the problem domain.
If you are going to expose state, expose it as a read-only property (e.g. public widget Foo { get ; private set ; }).

What is the difference...? [C# properties GET/SET ways]

I know in C# you can easily create accessors to a data type, for example, by doing the following:
public class DCCProbeData
{
public float _linearActual { get; set; }
public float _rotaryActual { get; set; }
}
However my colleague, advised me to do it this way:
public class DCCProbeData
{
private float _linearActual = 0f;
public float LinearActual
{
get { return _linearActual; }
set { _linearActual = value; }
}
private float _rotaryActual = 0f;
public float RotaryActual
{
get { return _rotaryActual; }
set { _rotaryActual = value; }
}
}
My way seems simpler, and more concise. What are the differences and benefits of doing it either way?
Thanks
Edit Just a note, my colleague was able to generate the code for the "second way" using the Refactor option within the Class Details pane most easily found in a Diagram file. This makes it easy to add many Properties without having to manually create the accessors.
"Your way" just tells the compiler to create the second option. Unless you do something else in the getter or setter, they are functionally identical.
However, with "your way", I would recommend using the proper C# naming conventions. I would personally write this as:
public class DccProbeData
{
public float LinearActual { get; set; }
public float RotaryActual { get; set; }
}
The only difference is that you've named the fields.
(I'd stick with your colleagues naming convention for public properties though.)
They do the same thing internally. The only difference is that you cannot directly access the backing field variable using Auto Implemented Properties.
They are technically the same... the get/set is shorthand (auto property).
Lots of questions on SO about this:
When to use get; set; in c#
What is the { get; set; } syntax in C#?
Auto-Implemented Properties c#
Your way doesn't allow you to initialize the values, and your colleague's way follows a more-standard naming convention.
I would like to add something that I haven't seen in the other answers, which makes #2 a better choice:
Using the first method you cannot set a breakpoint on the get and set.
Using the second method you can set a breakpoint on the get and set, which is very helpful for debugging anything accessing your private variable.
Okay, the names have been mentioned before. It's also worth noting that as well as not being with the normal .NET conventions, beginning a public name with an underscore is not CLS-compliant (indeed, one reason for using it for private names is precisely because of this, it makes the distinction clearer, and should result in a warning with some code-checkers if you accidentally have the wrong access level).
Names aside, the one advantage to the latter form is that you can add more complicated code. Still, it's a non-breaking change to go from the former style to the latter, so there's no reason to do it before it's needed.
The first way is the way to go when you need simple properties with get and set and private storage done for you.
Use the second way if you need to do something special when you get or set the value.
Also, I recommend you stick to naming conventions using FxCop or ReSharper.
I believe at the IL level, they both end up the same. In the background, VS creates autonamed variables for you when using the auto getters and setters.
The only way this could possibly be better is if you feel you will be adding more logic to the getters and setters at a later date.
Even then, this seems a little pointless.
They are the same in the sense that your code sample will automatically generate backing fields.
But the two code samples are different because the names of the properties are not the same (LinearActual vs linearActual)
There is no difference, however prior to C# 3 you had to use the long way. At the end of the day it's a C# feature - syntactic sugar. They are both functionally identical.
Things you can do when you don't use auto-implemented properties:
initialize to a default value
access or annotate the backing field (attributes)
read-only backing fields or immutability
set a breakpoint on access
have custom code around access to the variable
Use [System.ComponentModel.EditorBrowsableAttribute()] to enable custom logic on the accessors that you avoid accidently bypassing while coding
hides the backing field from intellisense
Conversion between the two ways is made very simple with ReSharper.
This is not to say don't use them by all means use them, unless you have a need for any of the other functionality listed.

Data encapsulation in C# using properties

currently I am thinking about data encapsulation in C# and I am a little bit confused.
Years ago, when I started to learn programing with C++, my professor told me:
- "Create a class and hide it data members, so it can't be manipulated directly from outside"
Example:
You are parsing an XML file and store the parsed data into some data members inside the parser class.
Now, when I am looking at C#. You have there properties. This feature makes the internal state / internal data of a class visible to outside.
There is no encapsulation anymore. Right?
private string _mystring;
public string MyString
{
get {return _mystring;}
set {_mystring = value;}
}
From my point of view there is no difference between making data members public or having public properties, which have getters and setters, where you pass your private data members through.
Can someone explaing me that please?
Thanks
The private data is encapsulated by the property itself. The only way to access the data is through the property.
In your situation above, there is little reason to use the property. However, if you later need to add some validation, you can, without breaking the API, ie::
private string _mystring;
public string MyString
{
get {return _mystring;}
set
{
if (IsAcceptableInput(value))
_mystring = value;
}
}
Remember that a Property, in .NET, is really just a cleaner syntax for 2 methods - one method for the property get section, and one for the property set section. It provides all of the same encapsulation as a pair of methods in C++, but a (arguably) nicer syntax for usage.
Well so properties aren't the wild west you are taking them to be at a first glance. The unfortunate truth of OOP is that a lot of your methods are getters and setters, and properties are just a way to make this easier to write. Also you control what you'd like the property to allow someone to do. You can make a property readable but not writable, like so:
private string _mystring;
public string MyString
{
get {return _mystring;}
}
Or as mentioned by Reed you can have your set method do a transformation or checking of any amount of complexity. For instance something like
private long myPrime;
public long Prime {
get { return myPrime; }
set {
if (prime(value) {
myPrime = prime;
}
else {
//throw an error or do nothing
}
}
}
You generally have all the value you get from encapsulation, with some syntactic sugar to make some common tasks easier. You can do the same thing properties do in other languages, it just looks different.
The benefit of properties is that later on, you could decide to add validation etc to the setter method, or make the getter method do some calculation or caching, and none of the code that already calls your property would need to change - since the class' interface remained stable
There still is data encapsulation, if you need it to be. Encapsulating data is not about hiding it from the client of the class or making it unaccessible, it's about ensuring a consistent interface and internal object state.
Let's say you have an object representing a stick shift car, and a property to set the speed. You probably know that you should shift gears in between speed intervals, so that's where encapsulation comes in.
Instead of simply making the property public, thus allowing public access without any verification, you can use property getters and setters in C#:
class StickShiftCar : Car
{
public int MilesPerHour
{
get {return this._milesPerHour;}
set
{
if (vaule < 20)
this._gearPosition = 1;
else if (value > 30)
this._gearPosition = 2;
...
...
this._milesPerHour = value;
}
}
While this example is not necessarily compilable, I am sure you catch my drift.
You may be missing the fact that you don't have to have properties to correspond to all class member fields. You can decide which properties to add to your class, and whether or not they will be accessible outside of the class.
Looking a bit deeper, why did your professor tell you to encapsulate? Just because it is the proper object-oriented design? Why is that the proper way? Programming languages and paradigms are just a way of coping with the complexity of getting a processor to run our code in an understandable way. There are two readers of code, the machine and humans. The machine will happily load data from, or branch to, any address in the memory space. We humans on the other hand like to think of "things". Our brains deal with "things" that have attributes or that perform actions. A lion will eat you, a spear can defend you, a lion is furry, a spear is pointy. So we can understand programs if they are modeled as "things". Properties are supposed to model the attributes of a thing, and methods are supposed to model the things actions. In practice it can become quite fuzzy and everything cannot be modeled as a real world action, but the effort to do so, when done well, can make a program understandable.
The very first attempt of using property to encapsulate the value is get;set;
But C# provide more advanced feature to enrich functions inside get and set to make the property read-only, write-only or with certain conditions.
For example, to set the value as
private string temp;
public string temp
{
get
{
return temp;
}
}
will be better than using:
public readonly string Temp;

C# 3.0 auto-properties — useful or not? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language.
I am used to create my properties in C# using a private and a public field:
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
Now, with .NET 3.0, we got auto-properties:
public string Title { get; set; }
I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.
In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.
I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.
So, what am I missing here? Why would anyone actually want to use auto-properties?
We use them all the time in Stack Overflow.
You may also be interested in a discussion of Properties vs. Public Variables. IMHO that's really what this is a reaction to, and for that purpose, it's great.
Yes, it does just save code. It's miles easier to read when you have loads of them. They're quicker to write and easier to maintain. Saving code is always a good goal.
You can set different scopes:
public string PropertyName { get; private set; }
So that the property can only be changed inside the class. This isn't really immutable as you can still access the private setter through reflection.
As of C#6 you can also create true readonly properties - i.e. immutable properties that cannot be changed outside of the constructor:
public string PropertyName { get; }
public MyClass() { this.PropertyName = "whatever"; }
At compile time that will become:
readonly string pName;
public string PropertyName { get { return this.pName; } }
public MyClass() { this.pName = "whatever"; }
In immutable classes with a lot of members this saves a lot of excess code.
The three big downsides to using fields instead of properties are:
You can't databind to a field whereas you can to a property
If you start off using a field, you can't later (easily) change them to a property
There are some attributes that you can add to a property that you can't add to a field
I personally love auto-properties. What's wrong with saving the lines of code? If you want to do stuff in getters or setters, there's no problem to convert them to normal properties later on.
As you said you could use fields, and if you wanted to add logic to them later you'd convert them to properties. But this might present problems with any use of reflection (and possibly elsewhere?).
Also the properties allow you to set different access levels for the getter and setter which you can't do with a field.
I guess it's the same as the var keyword. A matter of personal preference.
From Bjarne Stroustrup, creator of C++:
I particularly dislike classes with a lot of get and set functions. That is often an indication that it shouldn't have been a class in the first place. It's just a data structure. And if it really is a data structure, make it a data structure.
And you know what? He's right. How often are you simply wrapping private fields in a get and set, without actually doing anything within the get/set, simply because it's the "object oriented" thing to do. This is Microsoft's solution to the problem; they're basically public fields that you can bind to.
One thing nobody seems to have mentioned is how auto-properties are unfortunately not useful for immutable objects (usually immutable structs). Because for that you really should do:
private readonly string title;
public string Title
{
get { return this.title; }
}
(where the field is initialized in the constructor via a passed parameter, and then is read only.)
So this has advantages over a simple get/private set autoproperty.
I always create properties instead of public fields because you can use properties in an interface definition, you can't use public fields in an interface definition.
Auto-properties are as much a black magic as anything else in C#. Once you think about it in terms of compiling down to IL rather than it being expanded to a normal C# property first it's a lot less black magic than a lot of other language constructs.
I use auto-properties all the time. Before C#3 I couldn't be bothered with all the typing and just used public variables instead.
The only thing I miss is being able to do this:
public string Name = "DefaultName";
You have to shift the defaults into your constructors with properties. tedious :-(
I think any construct that is intuitive AND reduces the lines of code is a big plus.
Those kinds of features are what makes languages like Ruby so powerful (that and dynamic features, which also help reduce excess code).
Ruby has had this all along as:
attr_accessor :my_property
attr_reader :my_getter
attr_writer :my_setter
The only problem I have with them is that they don't go far enough. The same release of the compiler that added automatic properties, added partial methods. Why they didnt put the two together is beyond me. A simple "partial On<PropertyName>Changed" would have made these things really really useful.
It's simple, it's short and if you want to create a real implementation inside the property's body somewhere down the line, it won't break your type's external interface.
As simple as that.
One thing to note here is that, to my understanding, this is just syntactic sugar on the C# 3.0 end, meaning that the IL generated by the compiler is the same. I agree about avoiding black magic, but all the same, fewer lines for the same thing is usually a good thing.
In my opinion, you should always use auto-properties instead of public fields. That said, here's a compromise:
Start off with an internal field using the naming convention you'd use for a property. When you first either
need access to the field from outside its assembly, or
need to attach logic to a getter/setter
Do this:
rename the field
make it private
add a public property
Your client code won't need to change.
Someday, though, your system will grow and you'll decompose it into separate assemblies and multiple solutions. When that happens, any exposed fields will come back to haunt you because, as Jeff mentioned, changing a public field to a public property is a breaking API change.
I use CodeRush, it's faster than auto-properties.
To do this:
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
Requires eight keystrokes total.
#Domenic : I don't get it.. can't you do this with auto-properties?:
public string Title { get; }
or
public string Title { get; private set; }
Is this what you are referring to?
My biggest gripe with auto-properties is that they are designed to save time but I often find I have to expand them into full blown properties later.
What VS2008 is missing is an Explode Auto-Property refactor.
The fact we have an encapsulate field refactor makes the way I work quicker to just use public fields.

Categories

Resources