C# fields and properties [duplicate] - c#

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.

Related

explain public variable ; (vs) public variable {get; set;} difference in C#? [duplicate]

This question already has answers here:
What is the difference between a field and a property?
(33 answers)
Closed 9 months ago.
Similar questions has been asked a lot but it still doesn't make sense to me as I am beginner.
here is the link
What is the { get; set; } syntax in C#?
As that answer states
(I will be using age instead of "name" to avoid confusion)
Case 1
public class Genre
{
public int Age { get; set; }
}
and
Case 2:
public class Genre
{
private int age;
public int Age
{
get
{
return this.age;
}
set
{
this.age = value;
}
}
}
Both are the same things.
So for Case 1, where is private age variable?
Does it get declared in the backend.
If Yes, then what name will be assign to it?
Surely not (Age => age) Right?
It feels like,
public int Age { get; set; }
// is same thing as
public int Age;
Now, people have mentioned that one is property another is field. But they both can be used in similar way. So what is the difference on application level?
Can you please give me an example?
It feels like,
public int Age { get; set; }
is same thing as
public int Age;
Absolutely not, the first one is two functions, the setter and the getter, while the second one is a field, an integer. As a physical example of the difference, you can do ref Age in the second example, since it has a physical location in memory, but not in the first example, since it's just functions, it's code.
So for Case 1, where is private age variable? Does it get declared in the backend. If Yes, then what name will be assign to it?
Yeah, it gets generated for you by the compiler with a name you can't declare in C# because it contains invalid characters (that are valid in .Net in general). The actual name doesn't matter, just know that you can't possibly use it or collide with it.
The main difference between the two members in your last code snippet is encapsulation
See the "Encapsulation" part on this page:
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/oop
Hiding the internal state and functionality of an object and only allowing access through a public set of functions.
You asked about what private field gets generated if you use an automatic property. In fact the compiler will generate a private backing field usually called something like k__BackingField or similar.
For example, I created a basic class as follows:
public class Dog
{
public string Name { get; set; }
}
This definitely creates a field in the background, and I can find out by using ILSpy to decompile it and we see the following:
Notice the Name property is there as you'd expect, with its getter and setter. But notice also the k__BackingField.
When we inspect it, it is comprised of the following code:
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string <Name>k__BackingField;
So we can see that there is definitely a private field in the background being generated for the property. We can also confirm that it actually uses that field by inspecting the get_Name getter on the Name property:
[CompilerGenerated]
{
return <Name>k__BackingField;
}
The getter for the Name property indeed returns the private field that was compiler generated for us.
I think what you're stuck on is why we would do this. Basically, if you simply have a public field on a class, you're giving permission for all-and-any other classes to set and get that field without any kind of checks or balances or rules about what goes on when setting or retrieving that value. For small applications that aren't very complex, this won't create an issue for you. But in the future when you're writing bigger applications or libraries, when you want to guarantee certain functionality behaves the same way all the time, this best practice will be necessary.
There is no difference when you use them as simple variables but using a variable as property gives you the ability to perform a check or create an event handler. For example:
private int _onetoten;
public int OneToTen
{
get => _onetoten;
set
{
if ((value > 0) && (value < 11))
{
_onetoten = value;
}
}
}

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.

Why can fields be used as out/ref parameters and not properties? [duplicate]

This question already has answers here:
Difference between Property and Field in C# 3.0+
(10 answers)
Closed 9 years ago.
What makes properties and Fields different when we are passing Fields as an out/ref parameter . Does the difference between the two is memory allocation?
The biggest difference is that properties or indexers may not be passed as ref or out parameter (demo).
This is because properties do not necessarily have a backing storage - for example, a property may be computed on the fly.
Since passing out and ref parameters requires taking variable's location in memory, and because properties lack such location, the language prohibits passing properties as ref/out parameters.
Properties are not like fields at all, they're like methods.
this is a field; it does not have any logic.
private int _afield;
This is a property it defines a getter and a setter.
The getter and setter are methods.
public int AField
{
get
{
return _aField;
}
set
{
_aField = value;
}
}
This is a default property.
It's exactly like the previous property and field, except it does a lot of the work for you
public int BField { get; set; }
The best way to describe properties is in terms of the idiom of "getter" and "setter" methods.
When you access a property, you are actually making a call to a "get" method.
Java
private int _myField;
public int getMyProperty()
{
return _myField;
}
public int setMyProperty(int value)
{
_myField = value;
}
int x = getMyProperty(); // Obviously cannot be marked as "out" or "ref"
C#
private int _myField;
public int MyProperty
{
get{return _myField;}
set{_myField = value;}
}
int x = MyProperty; // Cannot be marked as "out" or "ref" because it is actually a method call

Property vs public declaration variable in a class [duplicate]

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.

Categories

Resources