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

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.

Related

C# Properties and fields [duplicate]

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.

Private Set or Private member?

I was wondering what's considered the C# best practice, private/protected members with public getters, or public getters with private/protected setters?
public int PublicGetPrivateSetter
{
get;
private set;
}
private int _privateMember;
public int PublicGetPrivateMember
{
get { return _privateMember; }
}
I feel that using a private member is more explicit in your code that it's a private setter (using naming conventions).
On the other hand using private setters gives you an option to use virtual (protected), write less code, has less room for mistakes and can give you an option to add a side effect later on if you need to.
I couldn't find what's considered a best practice, or even if one is considered better than the other. From what I've seen usually 80% of the time (from code that I'VE seen) people DONT use private setters... I'm not sure if this is because people don't know about private setters, or because it's considered better to actually use private members.
EDIT:
Indeed, other benefits which I forgot about when using private members is default values and the use of readonly.
I prefer to use auto-implemented properties unless the default implementation doesn't do what I want. So in this case, since the auto-implemented property does what you need, just use that:
public int Foo { get; private set; }
However another situation is if you want to make the field readonly (meaning that the only place where the field can be set is in the constructor). Then you need to define the backing field and mark it readonly as this isn't supported by auto-implemented properties:
private readonly int foo;
public int Foo
{
get { return foo; }
}
There is no best practice I'm aware of. I know automatic properties were mainly to make things easier even more easier for code generation and LINQ related stuff.
For me, I start with automatic properties and refactor later if needed. Depending on the need I may change something to virtual or protected as you mentioned, or maybe refactor to use a variable (When I want to refactor the set accessor to have some logic.
Its the same thing. In the first example, the compiler generates the backing store. In the second, you generated the backing store. Since the implementation is internal to the class, refactoring one into the other is not a big deal. Tools like Resharper make that trivial. The reason you probably haven't seen private setters that much is that its a C# 3.0 feature.
There's nothing wrong with private setters. In most case, it's used with auto properties to make the property readonly outside the object's scope.
Conceptualy speaking, it doesn't change anything. It's mostly a matter of taste.
I personnally use the private setter because I'm lazy and use the propg snippet a lot. (propg tab tab)
Also, most of the time I end up setting dirty flags and binding events to those properties, so I might as well do a part of the work right now. If you ever need to add a setter later, it's much easier if the code is written without using the member behind since the beggining as it will be less code to change.
There is no good answer to this question. the best pratice is to follow our compagnie nomenclature and if your alone then the way you prefer
In my opinion there is no best practice and very little (if any) difference in the resulting compiled code, it really just depends on your needs or own likes/dislikes. If you're following your group's naming standards and meeting requirements (e.g. don't need to propagate a change notification) then it shouldn't matter.
An advantage of private fields is that you can define a default value in the same place as your declaration. In an auto-implemented property you'll have do define the default in the constructor if it's not null or the type's default value.
However, I still like private setters. But we usually don't use auto-implemented properties since our setters usually have a richer functionality - e.g. property update notifications, logging, etc.

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#: Can I remove "{ get; set; }"?

Is there a difference between:
public T RequestedValue { get; set; }
and
public T RequestedValue;
?
Taken from this code:
public class PropertyChangeRequestEventArgs<T>:EventArgs
{
public PropertyChangeRequestEventArgs(T pRequestedValue)
{
RequestedValue = pRequestedValue;
}
public T RequestedValue { get; set; }
}
The first is an Auto-Implemented Property the second is a Field. Regular Properties expose Getters and Setters but have a private field to actually store the value:
private int someProperty;
public int SomeProperty
{
get { return someProperty; }
set { someProperty = value; }
}
The first allows you to change certain aspects of the implementation of your class without affecting all the other code in your application. The most important point is that, with properties, changes can be made without breaking binary compatibility (although a field can often be changed to a property without breaking code). If it is a public member, a property is advisable. (Stealing shamelessly from Snarfblam's comment)
From the Properties page:
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
Properties with a backing field are the most flexible form as they allow easy implementation of things like the INotifyPropertyChanged event for updating the UI in Model-View-ViewModel implementations.
deep explanation!
The {get; set;} is an automatic property, while the second is a field.
a field is a normal variable, from some type, that contains data.
a property is a couple of methods (well sometimes it's just one), one for get, and one for set. they only have a syntax like fields, but actually they are quite different.
properties are usually for filtering the set of the value, or virtualizing something in the get, etc.
automatic properties, also create a private field behind the scenes, return its value in the get, and set its value in the set.
seemingly this is just like a normal field, but behind the scenes (IL) using properties is totally different from using fields.
a.Property1 = 4;
is translate into something like:
a.Set_Propert1(4);
and this:
x = a.Property1;
is translate to something like this:
x = a.Get_Property1();
so why is it a good practice to use only public properties, even if they are automatic?
say you are writing a library, that is used by other application, and someday you want to release a new version of that library that constrains one of your class' fields..
if you are using properties, you can just change the property (even if it is an automatic one, you can replace it by a full one), and then any application which used your library can still use it in the same way.
but if you made a public field, which you now want to constrain, you'll need to make a property for this and make the field private, but if you will, any application that used you library will no more be bale to, because the way it use fields and property is different.
You may write:
public T RequestedValue { get; set; }
as a shortcut of:
private T _requestedValue;
public T RequestedValue
{
get { return this._requestedValue; }
set { this._requestedValue = value; }
}
They are totally equivalent, also considering the performance.
The answer is, yes you can remove the { get; set; } but then a whole load subtle differences kick in. Some will say fields and properties express radically different design intent but in practice this distinction has been eroded over the years as C# evolves and progressively blurs the the syntactic differences.
For a good list of compiler-binary level differences between fields and properties refer to SO question difference-between-property-and-field-in-c. But the answers to that question missed one significant point about the special role of properties when declaring interfaces.

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