Property vs public declaration variable in a class [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a field and a property in C#
what's the different between this:
class Name {
public int x;
}
and this:
class Name {
int cx;
public int x {
get { return cx; }
set { cx = value; }
}
}
is it the same thing or are there some differences?
Thank you

They are different.
In the first x is a Field, in the latter x is a Property. While Properties are "accessed just like Fields" in code, this is just the beauty of C#; the different definitions actually result in different incompatible types1.
Using auto-properties would be equivalent to the latter (but is much easier to write):
class Name {
public int x { get; set; }
}
I like this answer by Brian Rasmussen, to a related/duplicated question:
Fields and properties look the same, but they are not [the same]. Properties are methods and as such there are certain things that are not supported for properties, and some things that may happen with properties but never in the case of fields.
The answer then goes on to list some key differences covering usage and observable semantics.
1 Changing a Field to a Property (or vice-versa) is a type-breaking change and requires that early-bound (e.g. statically-typed) code is recompiled against the new type.

Related

C# - auto-properties VS pre-3.0 properties [duplicate]

This question already has answers here:
C# 3.0 auto-properties — useful or not? [closed]
(17 answers)
What is the difference between a field and a property?
(33 answers)
Closed 7 years ago.
Excuse me if my question is pretty much about code-style, but for simple cases which of the bellow is better?
CASE 1:
private static int number = 1;
public static int Number
{
get { return number; }
set { number = value; }
}
CASE 2:
public static int Number
{
get;
set;
}
I think case 2 is better because, when you have many properties in your class they won't consume so much space and the filesize will be reduced.
The syntax below is called auto properties, it doesn't matter in the terms of file size since in compilation time, a field is generated anyway (see, decompilation in the end of the answer) and there are get and set methods in the compilation results in both cases.
Auto properties allow you to keep your code more organized and short which is good for your code maintainability and readability, therefore you should prefer them when possible.
We will put aside the "In field without auto-property you can assign default value" topic for a second (also, it is possible now in auto-properties too in c# 6.0), sometimes, you want to run some more code inside the get or set methods of the property, like invoking event handles or validating the values, that's where standard property declaration comes into the picture, for example:
private int mNumber;
public int Number
{
get
{
return Number;
}
set
{
if (Number == 8)
{
throw new CannotReceive8Exception();
}
else
{
mNumber = value;
}
}
}
If you look at the decompiled code of this code:
public int Number { get; set; }
You will see that the compiler has added a background private field anyway:
While there is no difference to the compiler, since it would generate the fields for you, I prefer to leave my code clean and just use
public int Num {get;set;}
in one line, since there is no supreme meaning to explicitly typing the code and keeping it in one line allows me to differentiate properties like this from methods, which span across multiple lines at glance.

why to use accessors instead of plain assignment? [duplicate]

This question already has answers here:
Difference between Property and Field in C# 3.0+
(10 answers)
Closed 9 years ago.
why to use accessors in c#.net while we can use simple assignment like
public string name = "Haymen";
instead of doing this:
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
and how this property gonna set or return something since it don't have any way to set anything apparently ?
public class Movie
{
public int ID { get; set; }
}
Skeet has » an article about just that! Your case is covered by automatic properties, so you don't have all the writing work.
It depends on what your trying to do, you use accessors for a variety of reasons, one of which is to ensure that class properties are kept private and can only be directly manipulated internally.
An example :-
private int _myAge {get; set;}
public int MyAge
{
get
{
if(_myAge == null)
{
_myAge == GetMyAge();
}
return _myAge;
}
}
Use
public string name = "Haymen";
If you know for sure you will never need to debug the access to that variable (i.e. set a breakpoint when somebody reads/writes it).
If you know changing it will never effect the internal state of your object (i.e. side effect that you depend on or expect).
You want to have less lines to look at and you have met the above.
You want a "data only class" for XML Serialization and you don't want to create a lot of code to do the conversion for private methods (at least as of C# 3.5).
NOTE That being said, in general, you should not be exposing fields as public members. See here.

Properties with or without private fields [duplicate]

This question already has answers here:
Any reason to use auto-implemented properties over manual implemented properties?
(7 answers)
Closed 9 years ago.
What is more "true": use properties with or without private fields.
I.e.
1.
class A
{
int _field;
public int Field
{
get{ return _field;}
set{_field = value;}
}
}
2.
class A
{
public int Field{get;private set;}
}
Number 2 creates a backing field automatically, so you always have a private field "behind the scenes" (although not directly accessible in the latter case).
when you create anonymous property compiler creates corresponding field for you, so it's pretty much the same, but you can access autocreated field only via property
It makes no difference - the compiler generates the property implementation for you in exactly the same way that it generates a default constructor or the code for a using statement. These two classes are nearly 100% equivalent which you can see if you decompile an auto-property (the only difference is the name of the generated backing field that the compiler uses)
class A
{
public int Field {get; private set;}
}
class A
{
int _field;
public int Field
{
get { return _field; }
private set {_field = value; }
}
}
Its completely down to your personal preference.
As has already been stated, the second creates the backing field at compile time. You would typically define a backing field your self if you wanted the property to act as a public accessor to the field, where you can add custom logic or prevent the value being modified (using the private keyword on the setter).

Honestly, what's the difference between public variable and public property accessor? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
What is the difference between a field and a property in C#
Should I use public properties and private fields or public fields for data?
What is the difference between:
public string varA;
and
public string varA { get; set; }
The public property accessor gives you more flexibility in the future.
If you want to add validation to setting the value, you simply write a non-default setter. None of your other code would have to be modified.
There could also be reasons you'd want to replace the default getter with code. That can be a real pain with a public variable.
In addition to the other answers, you can also use a property to make the value read-only or even set-only:
public int Item { get; private set; } // read-only outside the class. Can only be set privately.
I have also run into situations where I later decide I want to proxy an object, or add AOP, which basically requires properties.
Public property accesses fields and internal class code through exposed getter and setter methods. A public field acesses the field directly.
Using propertys offers the potential to provide a layer of abstraction and design (ability to make set accessor protected, private).
When a property is specified and no body present an underlying private field is created by the compiler that is used to store the value against. Essentially:
private int item = 0;
public int Item {
get { return item; }
set {item = value; }
}
In general I tend to use properties for public exposed variables and fields for private. I might consider using a field if that field was accessed many times and speed was a crucial design requirement.

C# fields and properties [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the difference between a field and a property in C#
I don't understand the difference between field and properties in a class.
A field is a storage location for information. For example, if the field is of type int, it stores a 32-bit integer (a number from around minus 4 billion to around plus 4 billion).
A property is almost like a method or a pair of methods. It’s just code. No storage. For example, instead of
public int FortySeven
{
get
{
return 47;
}
}
you could also write
public int GetFortySeven()
{
return 47;
}
and it would be more or less the same thing; the only difference is that you write FortySeven (no parentheses) but GetFortySeven() (with parentheses).
Of course, properties can also have a setter, which means that
public int FortySeven
{
set
{
Console.WriteLine(value);
}
}
is pretty much the same thing as
public void SetFortySeven(int value)
{
Console.WriteLine(value);
}
and now instead of FortySeven = 47 you write SetFortySeven(47), but otherwise it is functionally the same.
An automatically-implemented property looks like this:
public int MyProperty { get; set; }
This code declares both a field and a property, but the field is invisible and you can only access the property. It uses the invisible field for its storage.

Categories

Resources