Difference between empty property declaration [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C# getters, setters declaration
What's the difference between these property declarations ? How do they work and why is one preferred.
public string aString {get;set;}
OR
private string bString = "";
public string aString
{
get { return bString; }
set { bString = value; }
}
NOTE : THis is not a urgent or important question , rather a matter of asking the people who know why something should be done a certain way. Also, please give examples of which scenario is best for each implementation.

First is automatic property and the second is classic property that we have known.
In C# 3.0 and later, auto-implemented properties make
property-declaration more concise when no additional logic is required
in the property accessors. They also enable client code to create
objects. 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.
When you don't have any special logic to add in the get and set part property then you can just use automatic property since its less code and less code means easier maintenance and less bugs.
You should switch to classic property syntax only if you need to add some logic (like validation) on the property.

Design:
Use second if you need to do something in exact moment of assignment (raise an event , change other fields, save undoredo information, write to a file and tons of other possibilities).
Practical: Use second if you need simply to debug, as you can not put a breakpoint on autogenerated property.
Use first in all other cases.

The most obvious difference is that you can't set the aString variable and return it, since you always return bString...

One difference is that in the case of automatic property you can't have a private setter. This is just a language shortcut or syntax sugar to make things easier to develop (also generated code looks cleaner...).
If you look at the compiled assembly the compiler made exact the same code as in the "classic" variation.

Related

Are properties just a simpler way of creating getter and setter? [duplicate]

This question already has answers here:
What are Automatic Properties in C# and what is their purpose?
(11 answers)
Closed 4 years ago.
I am learning about properties and I have a rather simple question:
Are properties just variables with "build-in" getter and setter?
What I mean can be described with this example.
int variable;
public void SetVariable(int _value)
{
variable = _value;
}
public int GetVariable()
{
return variable;
}
int variable { get; set; }
Are those two exactly the same or there is some slight difference that I don't see?
They are represented differently in the class. This is of practical importance if you use reflection, or if you use tools that use reflection. (You second example will show up in PropertyInfo, while your first would have to be found through FieldInfo plus MethodInfo plus application of some convention, a la bean conventions in Java.)
Because most developers most of the time don't deal directly with reflection, and because at best they don't think much about the indirect uses, it's easy to think of properties as just syntactic sugar around "field + getter + setter", but it can make a difference.
Edit: weirdly, when I initially answered I missed the (arguably) more important difference, which is how these things are used once declared. Yes you get (mostly) the same moving parts, but
In your first example,
variable = 37;
is a direct assignment that bypasses the setter logic. For this reason, it's likely you would declare variable as private and make the getter/setter public; so calling code would typically have to say
SetVariable(37);
instead.
In your second example, saying
variable = 37;
would call the variable's set method with the value 37.
Now again, this may seem meaningless since you're using the default setter in your example, but that needn't always be the case. It could be as simple as thread safety, or as complex as the value being transformed in some way rather than stored directly in an internal field.
And in the end you could still say it's syntactic sugar, but now it affects every bit of code that touches the variable, rather than just declaration of the variable itself.
In general, methods represent actions.
Properties represent data, Properties are meant to be used like fields, that meaning properties should not be computationally complex or produce side effects.
When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.

C# getters and setters method definition - beginner

I am new to C#. i was going through a tutorial. and it shows how to create accesor-mutator to a variable as shown below;
public String var1 {
get {return "";}
set {someVar = value;}
}
1.) Can't i create getters and setter like created in java
public getVar() {return "";}
public setVar(String x){var=x;}
2.) What is value used in C# ?
You can, but that's much more annoying to use, and ignores C# coding guidelines.
value is the implicit parameter to the setter. It contains the value that the caller is setting the property to. (the right side of the Property = something call)
See the documentation.
Sure you can. Properties in C# are designed to be syntactic sugar for just that. Under the hood a property is little more than a get/set method. It's just easier to create the two methods, it keeps the two methods in one place in the source code, it has simpler syntax for the caller, and properties that do nothing but just get/set a value are easier still to generate.
It's a keyword. It is the value that is being passed into the method. If someone enters obj.var1 = "abc"; then value will be a reference to "abc".
Sure, you can do it like Java. But why? Property syntax allows a much better experience from the caller's point of view.
value is a pseudo-variable that you can use to set your internal variable with, etc. It's equivalent to x in your Java-like example.
yes you can create getter setters as in java
example
int marks;
public void setMarks(int marks)
{
this.marks=marks;
}
public int getMarks()
{
return marks;
}

Is there a performance difference between setting a field by a method AND setting it by property? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Actual Performance of Fields vs. Properties
Is there a known performance difference between setting a field by method AND setting it via property?
(I just wonder if implementing a property emits some extra stuff to IL which makes the PROPERTY work slower than directly callind a method that sets the value)
Properties are methods. If you declare a property named MyProperty with both get/set then the compiler will emit two methods: get_MyProperty and set_MyProperty, decorating them to make understandable to others (who will use the property) that that methods are getter/setter of a property. For example the first version of managed C++ didn't hide this trick. Take a look to decompiled version of a method and a property setter (for example) and you'll see they aren't different, what you see in your code is sugar to make them "nice".

C# field vs. property [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between Property and Field in C#
I thought that basic properties ({ get; set; }) where the same as public fields, with only the advantage of being able to change them without breaking binary compatibility. Following the answer I got here https://stackoverflow.com/a/8735303/331785, I found out there is also a disadvantage to properties. They cannot be accessed by reference if they are of a value type. Why is this, and what other differences are there?
I found out there is also a disadvantage to properties. They cannot be accessed by reference if they are of a value type. Why is this
Because under the covers, a property is just a method. If you look at the IL, you'll see methods like get_PropertyName and set_PropertyName. The problem with that is in order to support working with references, you would need to be able to return a reference for a method.
public ref T MyProperty
{
get
{
return ref _underlyingField;
}
}
Update: Starting in C# 7.0, this is possible using the syntax describe above.
Remainder of previous answer:
This of course, is something entirely possible in the CLR; but not exposed by the C# language.
Though it is possible, the CLR needs some tweaks to keep it as verifiable. The syntax for the property would have to support it to.
However, is any of that useful? As you stated, a field can do it. If you need it; use a field. Supporting it would take a lot of work. There are probably a very few cases where it is appropriate; and would create many cases where just using a field might have been better in the first place.
Properties are just sugar-coating syntax for a getX() and setX() method. It looks and acts like a field, but it's really just two methods. The reason why the auto-property was added was to avoid the repetition of having to create a field and creating a standard getter and setter for the property, and to make it much simpler to allow changing the implementation without changing the interface.
The reason they can't be accessed by reference if they are a value type is because value types are generally on the stack and because you're just calling a method. The getter in the property has to be called and the returned value has to be pushed on the stack before it can be referenced.

Should I be using `this` by default? [duplicate]

This question already has answers here:
When do you use the "this" keyword? [closed]
(31 answers)
In C#, is "this" keyword required? [duplicate]
(6 answers)
Closed 9 years ago.
We all know that this refers to the actual instance of a class...but it seems to me that most people are not using it. So, should I be using it?
My thoughts about it are as follows: Since this refers to the actual instance of a class, it should be used to access any member of that class.
public void(String newValue) {
this.privateVariable = newValue;
}
This should guarantee that the value is not assigned to an object with the same name within the scope (which could also end up as undefined behavior, anyway). But, what if an underscore is used to separate private from non-private fields:
public voud(String newValue) {
_privateVariable = newValue;
}
this seems in that case a little redundant and unnecessary.
So, are there good reasons to use or not use this? Or am I just racking my brain about nothing?
Personally I only use it when it's necessary, e.g.
public MyClass(string name)
{
this.name = name;
}
I prefer that to renaming the parameter or field from the most natural name. I don't use this where it's otherwise unnecessary though. Having said that, there's absolutely no harm in doing so - and if you feel that it makes your code clearer, that's a very good reason to use it.
Nobody mentionned that you must use this if the requirement is to make a StyleCop compliant code and do not violate the readability rule SA1101. According to the documentation,
A violation of this rule occurs whenever the code contains a call to an instance member of the local class or a base class which is not prefixed with ‘this.’.
Also, in my opinion, using this keyword must be encouraged even for non-StyleCop-compliant source code, since specifying this increases readability and reduces the risk of mixing between local (method-scope) and class (object-scope) variables.
You should use the naming-convention approach. (The one with the undescore.)
There are dangers when changing code with the "this" approach if "this" is forgotten.
Why? If MyMethod in the followin class is later changed to include a local variable called "something" the compiler still compiles, while the code no longer does whats expected.
class MyClass
{
int something = 10;
void MyMethod()
{
//...lots'a code here...
something = 20; //Which var is something pointing at?
}
}
Changing it to the following will introduce a bug...
class MyClass
{
int something = 10;
void MyMethod()
{
int something = 0;
//...lots'a code here...
something = 20; //Which var is something pointing at?
}
}
So unless ALL developers working on your team, sharing code, always will remember "this"; don't go that way!
Personally I make sure that I never have name collisions between class members and locally declared variables. This means I never use this. However its all about readability really. If you think a "this" will make your code more intuitively understandable then use it, if not then don't.
I like using this. as it brings up intellisene which means I can quite often type a few letters of the method, variable and auto complete - makes writing code faster!
My two cents: Underscores are ugly!
=> fields are just camelCase
=> confusion with camelCase local variables is possible
=> always qualify with this
I used to use this all the time - probably a habit from pythons explicit self argument. I like to be reminded of when I use instance state.
Using Resharper from JetBrains made me brake that habit, since it would always flag this as redundant.
I use no special indicator for fields vs. locals (they are all ugly). I find that if it is getting harder to track which are which I'm better served by breaking up methods to be shorter with less local state. (The one exception is where the natural name of a parameter matches a field—most often occurs with constructors—then using this. to disambiguate.)
Edit: Added the one exception (thanks to other answers for reminding me).
It is subjective, but I prefer not to have it unless it provides unambiguity.
Using unnecessary this is like saying 'Create New Person'.
You choose :)

Categories

Resources