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.
Related
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.
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".
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.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
A lot of times the answer is merely when I want things to be allocated on a stack instead of the heap.. assuming I dont know what the stack and the heap are (and please dont try to explain it here), when exactly should I be using structs instead of classes?
Here is the answer I've been giving out, but please tell me if I'm wrong or falling short of a better answer:
I create structs usually when I have enums that I want to add more data to. For instance, I might start with a simple enum:
public enum Colors { Blue, Green, Red }
Then if I need to store more aspects of this data I go to structs:
public struct Color
{
string Name;
int HexValue;
string Description;
}
public class Colors
{
public static Color Blue;
public static Color Red;
public static Color Green;
static Colors()
{
Blue = new Color("Blue", 1234, "A light blue"
}
}
The point is... similar to enums, I use structs just when I want to declare a bunch of types.
struct vs class in .NET
The real time to use a struct is when you want value type like properties. Value types behave very differently from reference types, and the difference can be shocking and bug inducing if you aren't aware. For example a struct is copied into (and out of) method calls.
The heap vs stack isn't a compelling argument to me. In a typical .NET app, how often do you care about where the object lives?
I very rarely use structs in .NET apps. The only place I've truly used them was in a game where I wanted value type like properties for objects like vectors and such.
struct vs class in C++
This is a much simpler question to answer. structs and classes in C++ are identical to each other with only one minor difference. Everything in a C++ struct is public by default, where as everything in a C++ class is private by default. That is the only difference.
Simplistically, structs are for data, classes are for data and the manipulations of those data.
well in C++ land, you can allocate a struct (or class) on the stack or the heap... I generally use a struct when the default public access to everything is useful and class when I want to encapsulate... I also use structs for functors that need state.
You have this labelled with C#, C++ and "language-agnostic". The fact is though, the difference between structs and classes in C# and C++ are completely different, so this is not a language-agnostic question.
In C++ class is syntactic sugar for struct with different default visibility. The reason is that C had a struct and only had "public" visibility (indeed, it's not even a fully meaningful statement in C, there's no such thing as OO-style information hiding in C).
C++ wanted to be compatible with C so it had to keep struct default to everything visible. C++ also wanted to follow good OO rules, in which things are private by default, so it introduced class to do exactly the same, but with different default visibility.
Generally you use struct when you are closer to C-style use; no or relatively simple member functions (methods), simple construction, ability to change all fields from the outside ("Plain Old Data"). class is generally used for anything else, and hence more common.
In C# a struct has value semantics while a class has reference semantics (in C++ both classes and structs have value semantics, but you can also use types that access them with reference semantics). A struct, as a value-type is self-contained (the variable contains the actual value(s) directly) while a class, as a reference type refers to another value.
Some other differences are entailed by this. The fact that we can alias reference types directly (which has both good and bad effects) comes from this. So too do differences in what equality means:
A value type has a concept of equality based on the value contained, which can optionally be redefined (there are logical restrictions on how this redefinition can happen*). A reference type has a concept of identity that is meaningless with value types (as they cannot be directly aliased, so two such values cannot be identical) that can not be redefined, which is also gives the default for its concept of equality. By default, == deals with this value-based equality when it comes to value types†, but with identity when it comes to reference types. Also, even when a reference type is given a value-based concept of equality, and has it used for == it never loses the ability to be compared to another reference for identity.
Another difference entailed by this is that reference types can be null - a value that refers to another value allows for a value that doesn't refer to any value, which is what a null reference is.
Also, some of the advantages of keeping value-types small relate to this, since being based on value, they are copied by value when passed to functions.
Some other differences are implied but not entailed by this. That it's often a good idea to make value types immutable is implied but not entailed by the core difference because while there are advantages to be found without considering implementation matters, there are also advantages in doing so with reference types (indeed some relating to safety with aliases apply more immediately to reference types) and reasons why one may break this guideline - so it's not a hard and fast rule (with nested value types the risks involved are so heavily reduced that I would have few qualms in making a nested value type mutable, even though my style leans heavily to making even reference types immutable when at all practical).
Some further differences between value types and reference types are arguably implementation details. That a value type in a local variable has the value stored on the stack has been argued as an implementation detail; probably a pretty obvious one if your implementation has a stack, and certainly an important one in some cases, but not core to the definition. It's also often overstated (for a start, a reference type in a local variable also has the reference itself in the stack, for another there are plenty of times when a value type value is stored in the heap).
Some further advantages in value types being small relate to this.
Therefore in C# a struct when you are solely concerned with value-semantics and will not want to alias (string is an example of a case where value-semantics are very important, but you would want to alias, so it is a class to make it a reference-type). It's also a very good idea for such types to be immutable and an extremely good idea for such types to have fields that total to less than 16bytes - for a larger struct or a struct that needs to be mutable it may well be wise to use a class instead, even if the value-semantics make struct your first choice.
In C++, technically it doesn't matter. You could use struct for polymorphic object and class for PODs. The language wouldn't care, though your coworkers may plot a bloody revenge. Aside from default access, there's no difference between class and struct.
Ultimately, the most important consideration is that you pick a coding style, and apply it consitantly. Maybe that means everything is classes, or maybe PODs are structs. You need to decide for yourself, taking in to consideration any coding practices applied by whomever you work for.
As for myself, I only use structs if the object has only public members and no virtuals. They might have data only or data and methods. Typically I use structs for buckets of data that may or may not have simple operations associated with them, usually to convert from one type to another. Hence they may also have constructors.
When to use struct...
When you want object to behave as a value type
When the required size of object is <=16 bytes roughly.
A struct is actually exactly the same thing as a class - with one difference: in a class, everything is private by default while in a struct, everything is public by default!
struct Color
{
string Name;
private:
int HexValue;
};
would be the same as
class Color
{
int HexValue;
public:
string Name;
};
I would say , use stack when your data is smaller in size and you don't want a few thoushands of this object because it can hurt ou back a lot because as already mentioned that value types are copied by nature so pasing few thoushands of objects which is copied by value is not a good idea also.
Second point , i would like to include is when you only want data for most of the time and data is numeric most of the time , you can use stack.
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 :)