Properties with or without private fields [duplicate] - c#

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).

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;
}
}
}

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.

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.

automatic property with default value [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you give a C# Auto-Property a default value?
Is there any nice way to provide a default value for an automatic property?
public int HowHigh { get; set; } // defaults to 0
If not explicitly set anywhere, I want it to be 5. Do you know a simple way for it? E.g. I could set it in constructor or something, but that's not elegant.
UPDATE: C# 6 has got it: http://geekswithblogs.net/WinAZ/archive/2015/06/30/whatrsquos-new-in-c-6.0-auto-property-initializers.aspx
No, there isn't any nice way of doing this - basically you have to set it in the constructor, which isn't pleasant.
There are various limitations to automatic properties like this - my biggest gripe is that there isn't a way to create a read-only automatic property which can be set in the constructor but nowhere else (and backed by a readonly field).
Best you can do is set it in the constructor, you cannot make changes within automatic properties, you will need a backing field and implement the setter/getter yourself otherwise.
Using a backing field you can write something like this:
private int _howHigh = 0;
public int HowHigh { get {return _howHigh; } set { _howHigh = value; } }
If the default value for the type is not sufficient, then the only way to do it is via a constructor.
In a word: No.
Automatic properties are a one trick pony, as soon as you need something extra (like a reasonable default value) you should revert to the backing field regular properties.
I'm a Resharper user, and it makes going from automatic to backed properties a breeze.
The constructor is NOT the only option you have.
I believe this is best:
private int m_HowHigh = 5;
public int HowHigh {
get { return m_HowHigh; }
set { m_HowHigh = value; }
}
I prefer this for readability purposes more than the ctor().
This is NOT what you want:
[DefaultValue(5)]
public int HowHigh { get; set; }
Reference: http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx#Y2248
Because this is only a decoration and does not set the value (in C#4).

How to implement a read only property

I need to implement a read only property on my type. Moreover the value of this property is going to be set in the constructor and it is not going to be changed (I am writing a class that exposes custom routed UI commands for WPF but it does not matter).
I see two ways to do it:
class MyClass
{
public readonly object MyProperty = new object();
}
class MyClass
{
private readonly object my_property = new object();
public object MyProperty { get { return my_property; } }
}
With all these FxCop errors saying that I should not have public member variables, it seems that the second one is the right way to do it. Is this correct?
Is there any difference between a get only property and a read only member in this case?
The second way is the preferred option.
private readonly int MyVal = 5;
public int MyProp { get { return MyVal;} }
This will ensure that MyVal can only be assigned at initialization (it can also be set in a constructor).
As you had noted - this way you are not exposing an internal member, allowing you to change the internal implementation in the future.
C# 6.0 adds readonly auto properties
public object MyProperty { get; }
So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.
Versioning:
I think it doesn't make much difference if you are only interested in source compatibility.
Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.
Convention:
You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.
Serialization
Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer does only serialize public properties and not public fields.
Using an Autoproperty
Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.
Readonly field is selfdocumenting
There is one advantage of the field though:
It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.
But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.
With the introduction of C# 6 (in VS 2015), you can now have get-only automatic properties, in which the implicit backing field is readonly (i.e. values can be assigned in the constructor but not elsewhere):
public string Name { get; }
public Customer(string name) // Constructor
{
Name = name;
}
private void SomeFunction()
{
Name = "Something Else"; // Compile-time error
}
And you can now also initialise properties (with or without a setter) inline:
public string Name { get; } = "Boris";
Referring back to the question, this gives you the advantages of option 2 (public member is a property, not a field) with the brevity of option 1.
Unfortunately, it doesn't provide a guarantee of immutability at the level of the public interface (as in #CodesInChaos's point about self-documentation), because to a consumer of the class, having no setter is indistinguishable from having a private setter.
In C# 9, Microsoft introduced a new way to have properties set only on initialization using the init accessor, like so:
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
This way, you can assign values when initializing a new object:
var person = new Person
{
Firstname = "John",
LastName = "Doe"
}
But later on, you cannot change it:
person.LastName = "Denver"; // throws a compiler error
You can do this:
public int Property { get { ... } private set { ... } }
I agree that the second way is preferable. The only real reason for that preference is the general preference that .NET classes not have public fields. However, if that field is readonly, I can't see how there would be any real objections other than a lack of consistency with other properties. The real difference between a readonly field and get-only property is that the readonly field provides a guarantee that its value will not change over the life of the object and a get-only property does not.
yet another way (my favorite), starting with C# 6
private readonly int MyVal = 5;
public int MyProp => MyVal;
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties#expression-body-definitions
The second method is preferred because of the encapsulation. You can certainly have the readonly field be public, but that goes against C# idioms in which you have data access occur through properties and not fields.
The reasoning behind this is that the property defines a public interface and if the backing implementation to that property changes, you don't end up breaking the rest of the code because the implementation is hidden behind an interface.

Categories

Resources