C# getters and setters method definition - beginner - c#

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

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.

Setting a property of a property in a struct?

I created a struct, that has another struct as a property. I want to be able to do something like this:
MyColor.RGBColor.R = 255;
MyColor and RGBColor being the structs I created. This doesn't work, I set a whole new value to RGBColor, but that's not straightforward and there has to be an easier way. Currently, I have to do this:
MyColor.RGBColor = new RGBColor(255, MyColor.RGColor.G ...)
I'm pretty sure if I stopped encapsualting the private properties in public properties, and just make them public in the first place, I won't have this problem... but I always read that this is a bad thing to do, so how can I go about this? Thanks
EDIT:
This is how I implement the properties currently:
private rgbcolor _RGBColor;
public rgbcolor RGBColor {
get {
return _RGBColor;
}
set {
_RGBColor = value;
}
}
This is expected behavior. By accessing the property RGBColor, you invoke its getter method, which returns the struct's instance by value. Even though you would then assign (which, in fact, even doesn't compile) a value into R, the struct itself is not stored back into the RGBColor property — even if it had a setter. This is just how value types behave.
If you can, just avoid using structs. In the world of classes with automatic references and properties with getter/setter methods they tend to be very counter-intuitive. Trying to represent small classes (in terms of data size) as structs is premature optimization.
Note: What you call a “private property” is not a property. It's a member field.
You should look at conventions for class names vs. variable names. You seem to have it somewhat backwards in your implementation.
Here's what I think you're trying to do:
private rgbcolor _RGBColor = new rgbcolor();
public rgbcolor RGBColor {
get {
return _RGBColor;
}
}
Once that's in place, you should be able to do something like (assuming there's a property R on rgbcolor)
MyColor.RGBColor.R = 255;
This will work because the instance for MyColor.RGBColor will exist when the RGBColor property is accessed.
When you use value types (structs) you should keep in mind that passing them in methods as parameters or returning from methods (also in some other cases) always cause making a copy of that object. Properties are just the methods after compilation. So your code in fact equal:
var copy = MyColor.RGBColor; // you get a copy now
copy.R = 255; // and now you change a copy, not the original object's value
C# compiller understand that this is an error and don't compile your desired variant. Because of this it's strongly recomended to create imutable structs. In your case it's better to use classes.

Difference between empty property declaration [duplicate]

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.

Visual Studio 2010 - Break on anything that changes an object property

Is it possible in Visual Studio 2010 to break on anything (a method for example) that changes an object's property?
Or is it possible to find out if object properties changed in an ASP.NET Webforms application?
Update:
Correct answer can be found at: http://stackoverflow.com/questions/2682613/cant-set-breakpoints-on-an-auto-property-setter-why/6713920#6713920
If you have control over the code that declares the property, then certainly you can put a breakpoint inside the setter. Even if it is currently an auto-implemented property, e.g.:
public string SomeProperty { get; set; }
you can easily change it like this:
private string _someProperty;
public string SomeProperty {
get { return _someProperty; }
set {
// Set breakpoint here, or type Debugger.Break();
_someProperty = value;
}
}
If the value is actually a field instead of a property, you can still change it into a property to achieve the same thing.
If you don’t have access to the code that declares the property, then it’s quite a bit harder. Personally what I do is this, but it’s a bit laborious:
Declare a public static field in your Program class of the type that declares the property.
Early in the program, find a reference to the object whose property value changes and put that reference in this static field. If necessary, use Reflection to retrieve private fields.
Add global::MyNamespace.Program.MyField.ImportantProperty to the Watch window while debugging.
Step through the code until the value in the watch window changes.
It sounds like you're asking for a feature that would cause Visual Studio to break whenever a property / field is changed on an object.
For properties you can do this with normal breakpoints and a conditional. Simply set the breakpoint on the property setter, right click and select conditional. Then add a simple check to see if the new value and existing value are different
value != backingField
For fields there really is no good solution. The C++ debugger has a feature called Data BreakPoints which have exactly this behavior. But they are not available for managed languages, primarily because the CLR debugger does not support them. The best you can do is temporarily change your field to a property and use the above method.
Right click the red dot that represents the breakpoint - choose Condition and enter expression when you want the breakpoint to break the execution, or check Has changed to break whenever the value changes.
I don't think that there is a way in VS IDE that allows you to set a general breakpoint like that. If you really need this and willing to do some code changes, you can take a look at partial methods. Using partial methods, you define a partial method and call it from your setters. When you want to debug to find out who's calling a setter, you can provide a dummy implementation of the partial method. When you are done debugging, you can get rid of the implementation and the compiler will not generate anything related to that method as if it did not exist. This pollutes your code unless you can think of other potential uses of a partial method call from your setters. However, I just wanted to throw it out there so that you know.
You can use System.Diagnoistic.Debugger.Break() method for its purpose as follows
if(x!= y)
Debugger.Break()

C# property and ref parameter, why no sugar?

I just ran across this error message while working in C#
A property or indexer may not be passed as an out or ref parameter
I known what caused this and did the quick solution of creating a local variable of the correct type, calling the function with it as the out/ref parameter and then assigning it back to the property:
RefFn(ref obj.prop);
turns into
{
var t = obj.prop;
RefFn(ref t);
obj.prop = t;
}
Clearly this would fail if the property doesn't support get and set in the current context.
Why doesn't C# just do that for me?
The only cases where I can think of where this might cause problems are:
threading
exceptions
For threading that transformation affects when the writes happen (after the function call vs. in the function call), but I rather suspect any code that counts on that would get little sympathy when it breaks.
For exceptions, the concern would be; what happens if the function assigns to one of several ref parameters than throws? Any trivial solution would result in all or none of the parameters being assigned to when some should be and some should not be. Again I don't think this would be supported use of the language.
Note: I understand the mechanics of why this error messages is generated. What I'm looking for is the rationale for why C# doesn't automatically implement the trivial workaround.
Because you're passing the result of the indexer, which is really the result of a method call. There's no guarantee that the indexer property also has a setter, and passing it by ref would lead to a false security on the developer's part when he thinks that his property is going to be set without the setter being called.
On a more technical level, ref and out pass the memory address of the object passed into them, and to set a property, you have to call the setter, so there's no guarantee that the property would actually be changed especially when the property type is immutable. ref and out don't just set the value upon return of the method, they pass the actual memory reference to the object itself.
Properties are nothing more than syntactic sugar over the Java style getX/setX methods. It doesn't make much sense for 'ref' on a method. In your instance it would make sense because your properties are merely stubbing out fields. Properties don't have to just be stubs, hence the framework cannot allow 'ref' on Properties.
EDIT: Well, the simple answer is that the mere fact that a Property getter or setter could include far more than just a field read/write makes it undesirable, not to mention possibly unexpected, to allow the sort of sugar you are proposing. This isn't to say I haven't been in need of this functionality before, just that I understand why they wouldn't want to provide it.
Just for info, C# 4.0 will have something like this sugar, but only when calling interop methods - partly due to the sheer propensity of ref in this scenario. I haven't tested it much (in the CTP); we'll have to see how it pans out...
You can use fields with ref/out, but not properties. The reason is that properties are really just a syntax short cut for special methods. The compiler actually translates get / set properties to corresponding get_X and set_X methods as the CLR has no immediate support for properties.
It wouldn't be thread-safe; if two threads simultaneously create their own copies of the property value and pass them to functions as ref parameters, only one of them ends up back in the property.
class Program
{
static int PropertyX { get; set; }
static void Main()
{
PropertyX = 0;
// Sugared from:
// WaitCallback w = (o) => WaitAndIncrement(500, ref PropertyX);
WaitCallback w = (o) => {
int x1 = PropertyX;
WaitAndIncrement(500, ref x1);
PropertyX = x1;
};
// end sugar
ThreadPool.QueueUserWorkItem(w);
// Sugared from:
// WaitAndIncrement(1000, ref PropertyX);
int x2 = PropertyX;
WaitAndIncrement(1000, ref x2);
PropertyX = x2;
// end sugar
Console.WriteLine(PropertyX);
}
static void WaitAndIncrement(int wait, ref int i)
{
Thread.Sleep(wait);
i++;
}
}
PropertyX ends up as 1, whereas a field or local variable would be 2.
That code sample also highlights the difficulties introduced by things like anonymous methods when asking the compiler to do sugary stuff.
The reason for this is that C# does not support "parameterful" properties that accept parameters passed by reference. It is interesting to note that the CLR does support this functionalty but C# does not.
When you pass ref/out prepended it means that you are passing a reference type which is stored in the heap.
Properties are wrapper methods, not variables.
If you're asking why the compiler doesn't substitute the field returned by the property's getter, it's because the getter can return a const or readonly or literal or something else that shouldn't be re-initialized or overwritten.
This site appears to have a work around for you. I have not tested it though, so I can't guarantee it will work. The example appears to use reflection in order to gain access to the get and set functions of the property. This is probably not a recommended approach, but it might accomplish what you're asking for.
http://www.codeproject.com/KB/cs/Passing_Properties_byref.aspx

Categories

Resources