Is shorthand version of properties compared to fileds the same - c#

Is there any difference between these two classes from API/backward compatibility point of view:
Case A:
class Employee
{
public string Title { get; set; }
}
Case B:
class Employee
{
public string Title;
}
May I change from case B to case A without braking backward compatibility ?
Case C:
class Employee
{
public string Title { get { return T; } set { T = value; } }
private string T;
}
May I change from case B to case C too without breaking backward compatibility ?

Switching between A and C is fine. From a public point of view they are identical. An automatic property is still a normal property. It just spares you the work of defining a getter, setter and backing field manually.
B is different from both of them since a field is not a property.
In particular reflection distinguishes them(listing properties vs listing fields). For example typical property editors or some serializers only list properties but not public fields.
And of course only the field can be passed around as ref or out parameter. So such code breaks when you switch to a property.
For normal code they are usually source compatible, but not binary compatible. i.e. if you change between field and property without recompiling a dependent assembly it will break. But if you recompile both it will work is most cases.
This means a public field is not that bad in application code(but I'd still avoid it), but for library code you should really use a property.

Case A and C are identical (in case A backing field is genreated automatically by compiler).
No you can't change from B to either A or C without breaking backward compatibility - as you are changing field to proerties.

No, generally you can't.
You for example can't pass references to properties, only to fields (you can't pass a value of property by reference). The are also differences if some of the code using the class used reflection.

They are not the same: B uses a public field, A uses a public property. If any of the consumers of your class uses reflection to get to the field or passes the public field by reference, they will break, same goes for C.

Your two examples are not the same. The following two are the same:
class Employee
{
public string Title {get; set;}
}
and
class Employee
{
private string _title;
public string Title
{
get {return _title;}
set {_title = value;}
}
}

If you keep the names the same, then it shouldn't break backwards compatibility.
All the calls will be the same syntax-wise.
Problems may occur if you do it backwards. If you had a private variable and a property, the private variable may have been called in the class somewhere.

I want to make something clear that other people seem to be glossing over. While changing from B to C would not break a solution, this only works for things that are compiled together. If you are making an API or library which you want to reference in other projects and which you are not going to include in the solution (for example you are distributing the dll file to clients), changing from B to C will break clients using the API while changing from A to C will not.

Yes, you can, because you have declared the three classes private :-) :-)
Just kidding. Now... If you use StyleCop (or other similar "programs") they will mark all the public (and protected) (not-readonly nor const) fields as "bad things". This is because you can't change ANYTHING of them without breaking compatibility. The "right" thing to use a public field is not to use it, but to use a property (backed by a private field, or perhaps an internal field (but I'm not sure of this)). Now... A and C are "equivalent" against a "well behaved" user of the class (a "well behaved" user of the class uses only the public "interface" and doesn't use reflection).
To name a difference between A and B. You can pass ref and out of a field. You can't do it for a property (this is the "main" difference). The use of reflection on fields and property is different (it's OK to use public fields and properties through reflection)...

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 between public int i and public int i {get; set;} (what is the difference between automatic property and a public member?) [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
c#: why have empty get set properties instead of using a public member variable?
C#: Public Fields versus Automatic Properties
I am using "automatic" properties in my code,
and I wonder what is the actual difference between
this code:
public class foo{
public int i;
}
and
public class foo{
public int i {get; set;}
}
I know there is a difference, as sine 3rd parties that I've used missed the public members but found them once adding the {get; set;}.
AS there is no private field behind that, what is going behind the scene ?
A private field gets generated by the compiler when using automatic properties.
When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
In regards to the difference between the two examples - the first one exposes the field directly for manipulation. This is considered bad practice (think information hiding, loss of encapsulation).
With the second example, you must use the getter and setter and you can add any kind of validation and other logic around these actions.
See this blog post:
If I have a field with no special behavior, should I write a "just in case" property (with trivial get/set), or should I expose a public field?
The reason that the library design guidelines suggest you write a property here is that it is important that libraries be easily versioned. If you put a property in there ahead of time, you can change the property implementation without requiring users to recompile their code.
The first is a field and could be described as POD. The second is a property and allow for derived classes to overload and Shadow while the first does not. Also the second is a nicety since the complier silently creates a backing store.
That's an auto property, not an anonymous property. There is, in fact, a private backing field for it, it's just generated automatically by the compiler and isn't available to you at compile time. If you run your class through something like Reflector (or examine it at runtime with reflection), you'll see the backing field.
To answer your question of "What's the difference?", the obvious answer is that one is a field, whereas one is a property. The advantage to using auto properties is that it gives you the flexibility to move to traditional properties later, should the need arise, without changing your API. As far as third party code being able to "reach" one but not the other, that would be a question best answered by the other developer. That being said, most API's are designed to work on properties, not fields (since conventional wisdom is that you do not expose fields outside of the declaring class). If the third-party library is reflectively scanning your class, then it's likely only looking for properties.
The important thing to remember is that:
private string backingField;
public string Data
{
get { return backingField; }
set { backingField = value; }
}
and
public string Data { get; set; }
Are compiled to essentially the same code. The only substantive difference is the name of the backing field.

Doesn't this defeat the whole purpose of having read-only properties?

I know how to use properties and I understand that they implicitly call underlying get and set accessors, depending on whether we are writing to or reading from a property.
static void Main(string[] args)
{
A a = new A();
(a.b).i = 100;
}
class A
{
private B _b = new B();
public B b
{
get { return _b; }
}
}
class B
{
public int i;
}
What code (a.b).i = 100; essentially does is that first property’s get accessor returns a reference to an object _b, and once we have this reference, we are able to access _b’s members and change their values.
Thus, in our example, having read only property only prevents outside code from changing the value of a reference variable _b, but it doesn’t prevent outside code from accessing _b’s members.
So it seems that property can only detect whether we are trying to read from or write to a variable ( in our case variable _b ) located on the stack, while it’s not able to detect whether we’re trying to also write to members of an object to which the variable on the stack ( assuming this variable is of reference type ) points to.
a) But doesn’t that defeat the whole purpose of having read-only properties? Wouldn’t it be more effective if properties had the ability to also detect whether we’re trying to access members of an object returned by get accessor( assuming backing field is of a reference type )?
thank you
Immutability is not transitive; you can't expect mutable objects into an immutable accessor to be immutable.
Your reference is read only, not your object.
Imagine a class like this:
public class A
{
private List<int> _myList<int> = new List<int>();
public List<int> MyList { get { return _myList; } }
}
Now, users of the class can add and remove and access items in the list, but they cannot replace the list itself. This is important. It allows you to do things inside the class like assume the _myList member is never null, for example.
Put a more general way, this paradigm allows you do define an interface into your class such that users can use the types in the properties you expose, but they cannot just swap instances of complex types out from under you.
No, it does not defeat the purpose of read-only properties.
It is possible to use read-only properties that don't let the user change the underlying data. For example, you can have your property return a System.Collections.ObjectModel.ReadOnlyCollection even though the underlying type is a List. This, of course, won't prevent the user from changing the properties of the items in the collection.
Of course you can access B.i; it's public. You're thinking that since _b is private, all methods should be private when fetched through A? In that case it's pretty useless as you wouldn't be able to use B for anything.
You ask:
Doesn’t that defeat the whole purpose
of having read-only properties?
But look: your B.i member is a public field.
I ask you, then: what is the purpose of having a public field? It only makes sense if you want users of your code to be able to change that field's value. If you don't want that, it should be a private field, or (if you want to provide read but not write access) a property with a private set accessor.
So there's your answer. private B _b serves its purpose in the code you posted quite well (_b cannot be externally set to something new), just as public int i serves its purpose equally well (i can be externally changed).
Reference immutability is a popular feature request. Too bad its is so dramatically non CLS compliant. Very few languages have this notion, I only know of C++ (but don't get out much).
The key problem that this needs to be enforced by the CLR. C++ doesn't need to enforce this at runtime, only a C++ compiler is required to ensure that const contracts are observed. It has no support at all for language interop, beyond a bolt-on like COM.
This won't fly in .NET, there's little point in declaring a reference immutable and have that verified by the compiler when another language can stomp all over it because it doesn't have the syntax to express immutability. I reckon we'll get it some day, not Real Soon.
As a minor point, you don't have to write (a.b).i = 100; but simply
a.b.i = 100;
Back to your question, I don't think it defeats the purpose. You can still not do the following:
a.b = new B();
because there's no public set(). If you want the member i of class B to be read only, you can do the same thing as you did to member _b of class A by making it private and providing a public get(), but not set(). Off the top my head, doing what you propose might lead to many unexpected consistencies (I'm sure the language designers did not overlook this).
Entirely dependent on the situation, but read only access to a mutable object is a commonly used design. In many cases you simply want to ensure that the object itself remains the same.
Some classes (like String object in Java, and I believe in C# as well) are entirely immutable, where as others are only partially mutable. Consider an ActiveRecord style of object for which most fields are mutable, but the ID is immutable. If your class holds an ActiveRecord in a read only property, external classes cannot swap it for a different ActiveRecord object and thus change the ID, which might break assumptions within your class.
I disagree. Your property is for the class B, not for the members of class B. This means you can't assign a new Object to b. It doesn't mean that B's public members suddenly become private.
readonly applies to the class property, not the object that the property refers to. It keeps you from being able to write a.b = new B();, and that is all it does. It places no constraints on what you can do to the object once you get a reference to it. I think what you are discovering is that readonly make the most sense when applied to value types or immutable class types.
Another use case:
interface INamedPerson
{
String Name { get; }
}
class Bob : INamedPerson
{
public String Name { get; set; }
}
class Office
{
// initialisation code....
public INamedPerson TheBoss { get; }
public IEnumerable<INamedPerson> Minions { get; }
}
Now, if you have an instance of the Office, as long as you don't go cheating with casts, you have read-only access to everyone's names, but can't change any of them.
Ah. Encapsulation does the instantiated class inherit the containing class's access level. Exposing type B as a public property of type A. 'B.i' is public so it should be accessible from outside the same way 'A.b' is public.
A.b returns a reference of a privately accessible type B, however type B has a publicly accessible field i. My understanding is that you can set the i field of B but you can't set the b property of A externally. The B type property of A is readonly however the reference to type B does not define the same readonly access to its fields.
I'm sure you can modify the definition of type B to suit your need for the access level of B's fields or properties.

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.

Categories

Resources