what is the exact use of auto implemented properties [duplicate] - c#

This question already has answers here:
Public Fields versus Automatic Properties
(14 answers)
C# 3.0 auto-properties — useful or not? [closed]
(17 answers)
Closed 8 years ago.
May be its a duplicate question.
I did search about this and referred these Articles
use of properties vs backing field inside owner class,
should i prefer properties with or without private fields,
Properties Matter.
The point i understood was,
Access like making field read only
We can include some logics in
setter/getter used for data binding
What I really want to clear was,
public class Employee {
public string strName;
}
public class Employee {
public string strName {get;set;}
}
My questions:
Whats the difference between this two implementations
Is there any place ( i mean actual scenario) where we can justify a need for auto implemented properties instead the first implementation as shown above as first.
UPDATE
I know its a duplicate question and i mentioned it. Please consider my 2nd point in questions i asked.
what the answer precisely ?
I couldn't understand that.
Whether its a good practice or what is the need if i do not have any logic to set that value ?
Fine thank you all for replying. I got it now clear. Since i am very new i cant grasp it. But now i got the point. Sorry for wasting all your time.

With auto implemented properties you can do
public class Employee {
public string StrName {get; private set;}
}
And make an external read-only, but internal settable property. Which is something you can't do with your public variable

Having a field inside a class is not a good idea. using properties allows you to encapsulate your data better. and when you just want to have a field accessible without any logic in you class then you can use automatic properties.
there are many scenarios that using a field inside your class makes things go wrong and harder as your software evolve.
for example: assume you have
public class C
{
public int Value;
}
in your code base.
then suddenly you realize that Value can not be set to zero. Then you have to make Value private and provide a SetValue() and GetValue() method. This is easy. but wait, how you gonna handle all other codes that relies on Value now?
but think about this one
public class C
{
public int Value { get; set; }
}
now it just needs a backing field like _value and implementing the setter and getter.

Related

Why can't a field itself have getters/setters like properties do?

I'm a C# beginner, so easy explanations are greatly appreciated.
I was learning about properties, and got this question: properties give custom access logic to fields, but why can't the field itself contain its getter/setter? In other words, is there a reason why we can't get rid of Example and write custom get/setters under example(field)?
I could not find other posts that answer my question.
class MyClass
{
private int example = 5;
public int Example
{
get;
private set;
}
// here, this Example property only acts as a gateway for example.
// why is it not possible for the field 'example' to contain the
// get/set?
}
Property is an interface to Class, and not always is about storing data, you can always make the variable public member and will work perfectly like property, but the property has its own main job to work as an interface for that value with other classes.
While in many cases the property just works as public parameters, it is not always meant to be used in that way.

Is it a bad practice to replace every field in a class with a private property? [duplicate]

This question already has answers here:
Are there any reasons to use private properties in C#?
(19 answers)
Closed 8 years ago.
I tend to use private properties instead of private fields because they can be extended if necessary, so most of my model classes look like this:
public class MyClass
{
public MyClass(string name)
{
this.Name = name;
}
private string Name { get; set; }
private ISomeInterface SomeInterface { get; set; }
private bool IsSomething { get; set; }
public void Method(int parameter) { ... }
}
In other words, I usually replace private fields by private properties. Even inside the class context, properties are used, not fields. Most of them are auto-properties. Often I found out that my classes have no private fields at all (well, only the automatic backing fields for automatic properties).
I found this useful if you want to change the behavior (fields don't allow such flexibility).
I would like to know it this is a bad practice.
If it is a bad practice: WHY?
If it's not: do you think that I should use the "this" keyword inside the class to improve legibility?
Thanks!
That might be a matter of preference, but I don't like an idea of usage private properties instead of private fields:
There is very useful YAGNI principle which states not to do stuff which might be helpful in the future. Usually classes should not be like huge monsters, and you will be able very quickly wrap field into property when you will need it.
It's part of internal class implementation which you can change anytime without breaking clients of your class (very different story with public properties and fields - usually its better to use properties, even if you don't need to have some additional logic now).
As #dcastro pointed, there might not be any performance hit, but without compiler optimizations private fields have better performance than properties (which are methods).
Naming. I like to have private fields named with underscore, e.g. _name which allows me quickly distinguish between private and public members of class.
Sometimes I use private properties when I need some additional actions to be performed when I set some variable, or when value is computed based on other values, or when value is lazy-loaded. But when I do use, then I clearly see that something is happening there. That is very useful. If all fields would be properties, I would not have that hint.

Differences between getter and setter and a regular variable[C#] [duplicate]

This question already has answers here:
Auto-implemented getters and setters vs. public fields
(17 answers)
Difference between Property and Field in C# 3.0+
(10 answers)
Closed 8 years ago.
I've learned about the getter and setter topic and i couldn't understand the new type of this topic :
Let's say someone is declaring a new get&set method :
public int Id { get; set; };
What i want to know is what is the differences between doing what i wrote below and a regular public variable (public int id).
Comments are welcome.
Properties enhance the notion of encapsulation in OOP (oject oriented programming). That's the of a getter and setter in C#. Concretely, instead of using a simple variable class, you could use a property and a backing field in which actually your value will be stored. The property would be the way to access this backing variable and get it's value or altered it. The good thing about properties is that you can use any logic you want, before you store the value the user provide you. So instead of doing the same check in the methods of your class where this value is setted by the user and then used you could use your property.
Let we have a class called Customer where, one of it's fields is the customer's age.
public class Customer
{
private int age;
public int Age
{
get
{
return age;
}
set
{
if(age>0)
{
age = value;
}
else
{
throw new ArgumentException("age must be greater than 0.");
}
}
}
}
Having defined the above property, you avoid the check of the age that will be provide by the creator of an object of type Customer in any other place. the provided value will be stored somewhere that the creator/consumer of the object should not know (encapsulation) and in general terms would make you life as a programmer far easier.
So you contructor now will not contain any logic:
public class Customer(int age)
{
Age = age;
}
you simply assign the provided value to the corresponding property, without making any check about the validity of the provided value in your constructor.
Furthermore, say that in a method of your class some calculations are executed and the result is going to stored to variable called age. If you use it's corresponding property, you will not have again to make any validation check. This was a rather simple case with one variable. Try to think about what would have happened if you had 6 or 7 variables, a common case in production code.
The above are applicable wherever you have variables, whose values setting requires validation. On the other, if you class holds only varaibles, whose values aren't to undergo a validation testing, you could use the following syntax.
public class Customer
{
public int Age { get; set; }
}
This syntax, at first seems meaningless. Why we should declare this instead of the following one:
public class Customer
{
public int age;
}
The second declaration doesn't respect the principle of encapsulation (for more information about encapsulation in OOP, please refer here. Namely, the second declaration exposes the variable in which we will actually store the value of age.
In a few words, it wouldn't happened anything odd if you had use the second declaration and not the first one - provided that's there weresn't any logic in you value setting. However it's more consistent you use the first one.
A public property keeps the option open to perform validation or other logic while getting or setting the value. A public field does not.
For example:
- You might want to check that an age value isn't negative or ridiciously high
- You might want to make sure that when a first name is set, that it is properly cased
If you offer these properties as public fields you won't be able to enforce these rules later on.
You can also use properties to perform lazy instantiation, which might be useful when working with resource intensive code.

Properties vs Public member variables [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#
I'm a beginning programmer and I've read all about class properties. Books state that properties allow you to indirectly access member variables. Ok, so what makes it any different than just making the field public and accessing it directly?
Here's a quote from Learning C# 3.0 by Jesse Liberty:
For example, you might want external
classes to be able to read a value, but not change it; or you might want to write
some code so that the internal field can accept only values in a certain range. If you
grant external classes free access to your member fields, you can’t control any of that.
I don't understand what he is saying here. Can someone further explain this or give an example of why I would want to use a property over making the field public. As I understand it now they would both accomplish the same exact thing...so I'm obviously missing something here.
The other answers provided so far provide details of the advantages of accessor/mutator logic, but all seem to miss out on the ideological point about object encapsulation.
You see, class member fields are an implementation detail. If you have a class that represents a collection, for example, then you could implement it as a linked list (and expose the root-node via a public field) or you could implement it as a resizable array and expose the index0 member.
The problem with revealing implementation details is that you lose any kind of defined interface between your class and its consumers. By ensuring all operations are done via defined methods (controlled by the class itself) you make it easier to work with and provide for a long-term viewpoint. For example, you are far more easily able to convert your collection implementation from one type (the linked-list) to another (the array) without breaking any contracts with your class' consumers.
Don't worry about any performance impact of trivial accessor/mutator methods: the JIT compiler will inline the property methods. If you'll run some benchmarks you'll see the performance of properties vs fields is identical.
He's saying that properties can provide a getter but not a setter, therefore making them read-only (for example)
Properties are just syntactic sugar for a method e.g.
public int SomeProperty { get; set; }
is just sugar for
private int _someProperty;
public int SomeProperty_get()
{
return _someProperty;
}
public void SomeProperty_set(int value)
{
_someProperty = value;
}
This means that property setters/getters can apply logic that a mere public field can't
Edit: I'm not exactly sure what field names the CLR gives the backing fields for auto-properties - it's just an example :)
Edit2:
An example of a read only property:
public int SomeProperty { get; }
and finally a public read - private write (for autoproperties)
public int SomeProperty { get; private set; }
Really useful when you can't be bothered to type a backing field in :)
Just remember, if there is a possibility that you wish to apply logic to a member, then a property is the way to go. This is the way a lot of frameworks work (e.g. tracking 'dirty' objects by using a property to tell some sort of object manager that something has changed, this would not be possible using a public field)
Properties can have side-effects, They provide syntactic sugar around 'getter' and 'setter' methods.
public class MyClass {
int sizeValue = 0;
public int Size {
get {
return sizeValue;
}
set {
if ( value < 10 ) throw new Exception("Size too small");
sizeValue = value;
}
}
}
Properties can also have different levels of protection for get and set, you cannot do that with fields.
public class MyOtherClass {
// only this object can set this.
public int Level {
get; private set;
}
// only things in the same assembly can set this.
public string Name {
get; internal set;
}
}
There are a number of important differences between "properties" and "member access".
The most significant is that you can, through a property, make a member read-only (you can access the state, but you cannot change it). Just like "getter()" and "setter()" methods in Java.
You can also return a computed value from a property (generate a value "on-the-fly", as though it were a variable).
Properties can be configured so that:
they are read-only, Public MyProp {get;}
they are write-only Public MyProp {set;}
they are readable by external objects, but can only be set by the class's internals
Public MyProp {get; private set;}
As others have posted, you can also put logic into your getters and setters. For example before allowing the property to bet set to a new value, you can check that the value is acceptable.
You cannot do any of that with a public field.
Basically, a public field is the dumbest sort of property that you can have. Given that .Net now allows autobacking fields for your properties. There is no good reason to use public fields any longer.
If you have Public Int MyAge
I can set it to -200 or 20,000 and there is nothing you can do about it.
If you use a property you can check that age is between 0 and 150, for example.
Edit: as per IanNorton's example (man, that was fast)

Property accessors [duplicate]

This question already has answers here:
C# 3.0 auto-properties — useful or not? [closed]
(17 answers)
C# getters, setters declaration [duplicate]
(5 answers)
Closed 9 years ago.
Is there any fundamental difference between
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
and
public string Name {get; set;}
You can access internal field, in second case it's autogenerated
You can set a breakpoint in VS, in second you cannot.
Nothing fundamental, and you can usually change between them safely.... until something has used the field name (I'm looking at BinaryFormatter here...).
otherwise, no. You can usually change between the, without breaking things, for example to add logic or to add attributes to the field.
Basically there is no fundamental difference, #2 just saves you a lot of lines if you want to do this for 20 properties when you don't need encapsulation upfront but would like to have the option for future.
To external consumers of your class (assuming _name is private), they are the same unless you are using something like BinaryFormatter that uses reflection to store the internal state of your object.
To your class, the major difference is that you don't have access to the field when you use an auto property. This means you can't do some things, such as use the property as a ref or out parameter. For example, if you have a int value and you are reading the default value in your constructor, you can't say Int32.TryParse(s, out Range). You can say Int32.TryParse(s, out _range).

Categories