I'm a bit confused on the point of Automatic properties in C# e.g
public string Forename{ get; set; }
I get that you are saving code by not having to declare a private variable, but what's the point of a property when you are not using any get or set logic? Why not just use
public string Forename;
I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?
Properties can have code put into them without breaking contract, fields can't have code put into them without changing them to properties (and breaking the interface). Properties can be read only or write only, fields can't. Properties can be data bound, fields can't.
You can write
public string Forename{ get; private set; }
to get read-only properties... Still not nearly as versatile as real properties, but it's a compromise that for some works.
I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?
In the first case, the compiler will automatically add a field for you, and wrap the property. It's basically the equivalent to doing:
private string forename;
public string Forename
{
get
{
return this.forename;
}
set
{
this.forename = value;
}
}
There are many advantages to using properties over fields. Even if you don't need some of the specific reasons, such as databinding, this helps to future-proof your API.
The main problem is that, if you make a field, but in v2 of your application, need a property, you'll break the API. By using an automatic property up front, you have the potential to change your API at any time, with no worry about source or binary compatibility issues.
It is meant that you expect to add the logic later.
If you do so and have it as property from the beginning, you will not have to rebuild the dependent code. If you change it from a variable to a property, then you will have to.
Consider looking at some related threads about Difference Between Automatic Properties and Public Fields, Fields vs Properties, Automatic Properties - Useful or Not?, Why Not to Use Public Fields.
Public data members are evil (in that the object doesn't control modification of it's own state - It becomes a global variable). Breaks encapsulation - a tenet of OOP.
Automatic properties are there to provide encapsulation and avoid drudgery of writing boiler plate code for simple properties.
public string ID { get; set;}
You can change automatic properties to non-automatic properties in the future (e.g. you have some validation in a setter for example)... and not break existing clients.
string m_ID;
public string ID
{
get { return m_ID; }
set
{
//validate value conforms to a certain pattern via a regex match
m_ID = value;
}
}
You cannot do the same with public data attributes. Changing a data attribute to a property will force existing clients to recompile before they can interact again.
When adding auto properties the compiler will add get set logic into the application, this means that if you later add to this logic, and references to your property from external libraries will still work.
If you migrated from a public variable to a property, this would be a breaking change for other libraries that reference yours - hence, why not start with an auto property? :)
For one, you can set the property to virtual and implement logic in an inheriting class.
You can also implement logic in the same class afterwards and there won't be side-effects on any code relying on the class.
Not all properties need get/set logic. If they do, you use a private variable.
For example, in a MV-something pattern, your model would not have much logic. But you can mix and match as needed.
If you were to use a field like you suggested in place of a property, you can't for example define an interface to describe your class correctly, since interfaces cannot contain data fields.
A property is like a contract, and you can change the implemenation of a property without affecting the clients using your classes and properties. You may not have any logic today, but as business requirements change and if you want to introduce any code, properties are your safest bet. The following 2 links are excellent c# video tutorials. The first one explains the need of properties over just using fields and the second video explains different types of properties. I found them very useful.
Need for the Properties in C#
Poperties in C#, Read Only, Write Only, Read/Write, Auto Implemented
Take a look at the following code and explanation.
The most common implementation for a property is getter or a setter that simply reads and writes to a private field of the same type as a property. An automatic property declaration instructs the compiler to provide this implementation. The compiler automatically generates a private backing field.
Look into the following code:-
public class Stock
{
decimal currentPrice ; // private backing field.
public decimal CurrentPrice
{
get { return currentPrice ; }
set { currentPrice = value ; }
}
}
The same code can be rewritten as :-
public class Stock
{
public decimal CurrentPrice { get ; set ; } // The compiler will auto generate a backing field.
}
SOURCE:- C# in a Nutshell
Related
I often see properties in classes, instead of fields. It looks like that:
class TestClass
{
public ulong Id { get; set; }
public string Description { get; set; }
}
Why peoples do this? They could use fields instead. I see at least single pro there - we can pass fields with ref keyword into functions. Is there any pro for properties or other reasons to use them like that?
The main reason is encapsulation - the value can only be changed trough the corresponding properties, and this continues to be the case even if you later decide that the property shouldn't just return a value. Maybe you find that you'll want to fire an event when a value changes? If you've got a property, that's very easy. If you've got a public field, you need to make a breaking change.
In addition, properties can be virtual or declared in interfaces. And they can be declared read-only.
Oh, and it helps in debugging: You can set a breakpoint on the "set", if you want to know who is changing your value (unexpectedly).
People use properties instead of fields mainly due to coding conventions. If it doesn't perform any actual encapsulation (in case of POCO), then there's not much of a difference in C#. Most of the times fields could be used instead of properties with no consequences whatsoever.
// This:
public string MyValue;
// Could be later on changed to this:
public string MyValue { get; set; }
// With no compatibility issues.
Although it's interesting to speculate why conventions are the way they are. In C# difference between properties and fields is mostly hidden from consumer standpoint. This is not necessarily the case in older languages. I.e. in Java you had to write getter and setter methods explicitly. So if you have a field in Java, and now you decide that you want to encapsulate it, then you would need to go over all usages of that field and use getters and setters instead. This could be even a bigger issue if you use dynamic library linking (that used to be popular style of deployment some time ago). Because of this it was easier to encapsulate fields from the start, so you wouldn't have backwards compatibility issues in the future. Naturally these conventions spread to other languages as well.
I failed to understand why auto implemented property language feature exist in C# 3.0.
What the difference it is making when you say
public string FirstName;
than
public string FirstName { get; set; }
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...
Just to add to what other people have said, declaring a public field, the field is accessible for read and write. declaring public automatic property, although the property is public, you can still add modifier to control the accessibility at the get/set level.
public string FirstName { get; private set; }
The user of your class sees FirstName as public property. However, he/she cannot write to it.
Consider what happens if you later want to change each of them to a property with a custom implementation. If it's an automatically implemented property, you just add a field and change the implementation. Full source and binary compatibility.
If it's a field to start with, you get neither source nor binary compatibility. You have to rebuild everything that references it, and fix up anything which no longer compiles.
Additionally, properties have various benefits over fields. My main personal objection to fields is that it exposes an implementation decision in the API.
The difference is that other assemblies compiled with code that read the property is compiled against a property.
If you later on decide you need to add code to the getter or setter, you can do that, without having to force every other assembly linked to it to recompile.
Not so with fields. If you later on change a field to be a property, in order to add that code, other assemblies linked against yours will cease to function properly since they're compiled to read a field, not a property.
Also, lots of code is written to find properties, not fields, like data binding and similar.
because of this use:
public string FirstName { get; private set; }
easy property, that 'kosher' by OO rules
The first is a public field, while the second is a public property.
The main difference is in how they are used. For example WPF can only data bind to properties, not fields.
Auto properties are Compiler generated regular properties, they use a backing fields like any regular property but you don't need to write the code for that. Here is a very illustrative sample (thanks to Reflector) of the code generated by the compiler:
[CompilerGenerated]
private string <ContentType>k__BackingField;
public string ContentType
{
[CompilerGenerated]
get
{
return this.<ContentType>k__BackingField;
}
[CompilerGenerated]
set
{
this.<ContentType>k__BackingField = value;
}
}
What is the difference in functionality between using a field with get and set methods versus using a property to attribute a value to an object through a class? For example, when setting up a value val in a class, are there any reasons to choose one of the two classes below over the other (other than length of code written and interface compatibility):
class FieldTest
{
public FieldTest()
{
}
private string val;
public void SetVal(string temp)
{
val = temp;
}
public string GetVal()
{
return val;
}
}
Versus
class PropertyTest
{
public PropertyTest()
{
}
public string val { get; set; }
}
Tested Usage in Visual Studio 2010:
class TestFunctions
{
static void Main(string[] args)
{
FieldTest Test_Fields = new FieldTest();
Test_Fields.SetVal("Test");
string temp_str = Test_Fields.GetVal();
PropertyTest Test_Property = new PropertyTest();
Test_Property.val = "test";
string temp_str_prop = Test_Property.val;
System.Windows.Forms.MessageBox.Show("Field: " + temp_str + "\n\nProperty: " + temp_str_prop);
}
}
I know only a field can use ref and out keywords, but the other advantages usually attributed to a property--encapsulation, versioning, etc-- seem to be the same with these two setups.
I've checked articles such as Difference between Property and Field in C# 3.0+ and What is the difference between a Field and a Property in C#?. Though they give good descriptions of the ideas behind properties and fields, I have not been able to find a specific answer to my question.
Thanks in advance for clarification.
EDIT 2015-07-29:
I believe this to be a separate question from other StackOverflow answers, such as those found here, as these answers did not seem to specifically address using fields with their own get and set methods as a replacement for a property.
My statement above, "I know only a field can use ref and out keywords..." comes from answers similar to the following (found here):
"Fields may be used for out / ref parameters, properties may not. Properties support additional
logic – this could be used to implement lazy loading among other things."
The functionality is almost identical. For "normal" code use-cases, these snippets will act exactly the same, as a property is in effect just a hidden field with two hidden methods (get and set).
However, there is a difference when it comes to reflection. Properties show up as PropertyInfo, and methods MethodInfo. You also can only bind to properties (in WPF/WinRT). Serialization also only works against properties. Both of these (and doubtlessly others) fail because they use reflection to find the members to act against.
So depending on your use case, they are the same. Generally speaking, I would stick with properties.
In the .NET world properties are how you attribute data to objects. Methods are typically actions associated with the objects. Fields usually store internal (private) object instance state.
Under the hood, read/write property accessors get compiled to get and set methods.
Additionally, many technologies do not work with methods. Data Annotations, Entity Framework, and serialization are a few that pop instantly to mind.
I would always vote for properties rather than getter and setter.
First of all - using Property is neat and clean. The code is more clear, less junky and easy to understand.
If you use Automatic Property you just need one line of code for one Property where you need at least 6 for a getter and setter approach. So if your class has 20 attributes then total 120 lines of codes? Oh Man!!!
but the other advantages usually attributed to a property--encapsulation, versioning, etc-- seem to be the same with these two setups. => I disagree, consider a scenario where you want to force all implementation of an interface with an attribute to be readonly. That is easily doable with a readonly property in the interface. Now try that with getter and setter. Frankly you can't.
Then there comes Serialization. You cannot serialize a computed value unless that is a property. Methods are never serialized.
Let's take a look at your second code:
class PropertyTest
{
public PropertyTest()
{
}
public string val { get; set; }
}
As said in the Auto-Implemented Properties page on MSDN, when you declare an auto-implemented property like in your example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
In other words, it would be like writing this code:
public class PropertyTest
{
public PropertyTest()
{
}
private string _val;
public string val
{
get { return _val; }
set { val = value; }
}
}
So, properties are a way to encapsulate fields. As you can see on MSDN, too:
A property is a member that provides a flexible mechanism to read,
write, or compute the value of a private field. 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.
In my opinion, you should always prefer to use the property implementation than the getter/setter methods. Not because it seems cleaner and flexible to make things like compute values, but it is actually easier to implement (you write less code on auto-implemented properties).
We could say that there are almost no difference from the properties than the getter/setter methods too, if we look at the part where MSDN says "but they are actually special methods called accessors". But again, we have the example of brainless coder above, we have Framework behaviours that encourages us to use properties: methods can not be serialized, while properties can.
Seen a few examples of code where this happens:
public class Foo
{
string[] m_workID;
public string[] WorkID
{
get
{
return m_workID;
}
private set
{
m_workID = value;
}
}
}
What's the point of this?
Since the use m_workID unnescessary.
In general, the point is to separate implementation (the field) from API (the property).
Later on you can, should you wish, put logic, logging etc in the property without breaking either source or binary compatibility - but more importantly you're saying what your type is willing to do, rather than how it's going to do it.
I have an article giving more benefits of using properties instead of public fields.
In C# 3 you can make all of this a lot simpler with automatically implemented properties:
public class Foo
{
public string[] WorkID { get; private set; }
}
At that point you still have a public getter and a private setter, but the backing field (and property implementation) is generated for you behind the scenes. At any point you can change this to a "normal" fully-implemented property with a backing field, and you'll still have binary and source compatibility. (Compatibility of serialized objects is a different matter, mind you.)
Additionally, in this case you can't mirror the behaviour you want (the ability to read the value publicly but write it privately) with a field - you could have a readonly field, but then you could only write to it within the constructor. Personally I wish there were a similar shorthand for this:
public class Foo
{
private readonly int id;
public int Id { get { return id; } }
...
}
as I like immutable types, but that's a different matter.
In another different matter, it's generally not a good idea to expose arrays like this anyway - even though callers can't change which array WorkID refers to, they can change the contents of the array, which is probably not what you want.
In the example you've given you could get away without the property setter, just setting the field directly within the same class, but it would mean that if you ever wanted to add logging etc you'd have to find all those writes.
A property by itself doesn't provide anywhere to put the data - you need the field (m_workID) for storage, but it entirely correct to hide that behind a property for many, many reasons. In C# 3.0 you can reduce this to:
public string[] WorkID {get; private set;}
Which will do much of the same. Note that exposing an array itself may be problematic, as there is no mechanism for protecting data in an array - at least with an IList<string> you could (if needed) add extra code to sanity check things, or could make it immutable. I'm not saying this needs fixing, but it is something to watch.
In addition to the Object Oriented philosophy of data encapsulation, it helps when you need to do something every time your property is read/write.
You can have to perform a log, a validation, or any another method call later in your development.
If your property is public, you'll have to look around all your code to find and modify your code. And what if your code is used as a library by someone else ?
If your property is private with appropriate get/set methods, then you change the get/set and that's all.
You can use C# 3.0 auto properties feature to save time typing:
public class Foo
{
public string[] WorkID
{
get; private set;
}
}
In addition properties gives you lot of advantages in comparison to fields:
properties can be virtual
properties hide implementation details (not all properties are just trivial variable accessors)
properties can contain validation and logging code and raise change events
interfaces cannot contains fields but properties
A lot of times you only want to provide read access to a field. By using a property you can provide this access. As you mention you may want to perform operations before the field is accessed (lazy loading, e.g.). You have a lot of code in there that just isn't necessary anymore unless you're still working in .Net 2.0-.
I failed to understand why auto implemented property language feature exist in C# 3.0.
What the difference it is making when you say
public string FirstName;
than
public string FirstName { get; set; }
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...
Just to add to what other people have said, declaring a public field, the field is accessible for read and write. declaring public automatic property, although the property is public, you can still add modifier to control the accessibility at the get/set level.
public string FirstName { get; private set; }
The user of your class sees FirstName as public property. However, he/she cannot write to it.
Consider what happens if you later want to change each of them to a property with a custom implementation. If it's an automatically implemented property, you just add a field and change the implementation. Full source and binary compatibility.
If it's a field to start with, you get neither source nor binary compatibility. You have to rebuild everything that references it, and fix up anything which no longer compiles.
Additionally, properties have various benefits over fields. My main personal objection to fields is that it exposes an implementation decision in the API.
The difference is that other assemblies compiled with code that read the property is compiled against a property.
If you later on decide you need to add code to the getter or setter, you can do that, without having to force every other assembly linked to it to recompile.
Not so with fields. If you later on change a field to be a property, in order to add that code, other assemblies linked against yours will cease to function properly since they're compiled to read a field, not a property.
Also, lots of code is written to find properties, not fields, like data binding and similar.
because of this use:
public string FirstName { get; private set; }
easy property, that 'kosher' by OO rules
The first is a public field, while the second is a public property.
The main difference is in how they are used. For example WPF can only data bind to properties, not fields.
Auto properties are Compiler generated regular properties, they use a backing fields like any regular property but you don't need to write the code for that. Here is a very illustrative sample (thanks to Reflector) of the code generated by the compiler:
[CompilerGenerated]
private string <ContentType>k__BackingField;
public string ContentType
{
[CompilerGenerated]
get
{
return this.<ContentType>k__BackingField;
}
[CompilerGenerated]
set
{
this.<ContentType>k__BackingField = value;
}
}