Is property a container and accessor in C#? - c#

I have this property in my Class:
public string A
{
set
{
A = value;
}
}
It gives me an error whenever I try to assign a value to A. Actually, my IIS Express stops and gives no clue.
I have a feeling that this creates an endless assignment of value to A, it's like a recursion. My questions:
What is happening in my code?
Is property just an accessor (getter/setter) and not a container when you specify an implementation?
When using auto-implemented property, is the property both container and accessor?

You'll have a StackOverflow exception, since you're assigning the property itself in its setter, which results in an endless assignment.

You can not set property variable itself as a container..
you can write like this.
Scenario 1:
public string A
{
set;
}
Scenario 2:
private string _A=String.Empty;
public string A
{
set{_A=value;}
}
let me know if any question.

When you are using an auto implemented property, the compiler generates a container for the value and methods to work with that container (get and set).
When you implement the propriety yourself, like you did, the compiler only generates a set method, that then calls itself, resulting in an endless loop. The correct way to do it would be:
private string _a;
public string A
{
set
{
_a = value;
}
}
In this case, the compiler will generate a method to set the value of _a , and no recursion occurs.

Related

making a variable only settible through its set property

I have a boolean variable, I want every change to its value to invoke a piece of code.
my current solution is the following:
bool _manualControl;
bool manualControl {
get {
return _manualControl;
}
set {
this._manualControl = value;
GlobalEventManager.ManualControlEvent?.Invoke(value);
}
}
this solution has two problems:
the value of "_manualControl" can be changed internally without invoking my piece of code, I want to prevent that.
I would prefer to avoid using two variables to get the desired behavior.
Is there any way to achieve what I want while avoiding these two specified issues?
You can set the property to be public and have a private backing field that can only be modified from within the class, which you have control of.
Or you could use an Aspect Oriented Programming framework like PostSharp, which would allow you to use an auto property and annotate it with the behaviour you desire. This would remove the need for you to have a backing field.
To me this sounds a bit like you want to solve an architectural problem, aka code smell. Why is it that you fear your field might be set outside your setter? Is it a particularly large class that a lot of people are chaning without really knowing what it is doing?
Why even have code in the setter? Like you could just redesign your code to have a method do what your setter code does and introduce that into your code flow / process.
And have a Unit Test validate your desired behavior.
If you want to:
ensure that the setter code always executes when a new value is assigned (inside and outside of the class)
avoid having two members in the class, that represent a single value
Then this can be approached by wrapping the value within a struct like one below:
struct Intercepted<T>
{
private readonly Action<T> _onChange;
private T _value;
public Intercepted(Action<T> onChange, T initialValue = default(T))
{
_onChange = onChange;
_value = initialValue;
}
public T Value
{
get
{
return _value;
}
set
{
_value = value;
_onChange?.Invoke(value);
}
}
}
In the class, ManualControl can now be represented with a single member, of type Intercepted<bool>:
public Intercepted<bool> ManualControl { get; } = new ManualControl(
onChange: newValue => {
GlobalEventManager.ManualControlEvent?.Invoke(newValue);
}
);
The value can be accessed like this:
// from within the class
if (ManualControl.Value) { ... }
// from outside
myObj.ManualControl.Value = true;
Now there is no way to change the value without triggering the setter code, both inside and outside the class.

Purpose of property with empty set get

Can someone tell me, what is the porpose of using a public property for a private class member but not implementing anything in the set and get part? I know that it could be just for examples and that later on you can implement something but I don't know if there is any meaning using it like that
I am going to assume you know there is a private field generated by the C# compiler as the field backing up this property. It is syntactic sugar. I am also going to assume you know this is an auto-implemented property. So what is the point of a property if it public with no logic in the get or set. In other words, any class can access it and set its value. So why choose this property over a public field?
Purpose of it is:
Today the get and set is empty but it may need code in the future. To avoid breaking a contract in the future, you use an empty get and set.
Most .NET databinding can be done against properties but not fields. So although it is empty, it still serves a far greater purpose.
The get and set can have access modifiers. For example, you can say set is private but get is public.
A field cannot be used in interfaces but properties can.
This is an "auto-implemented" property in C#. In effect, the property acts as a full property, i.e.:
This:
public int Number { get; set; }
Is equivalent to:
private int _number;
public int Number
{
get
{
return this._number;
}
set
{
this._number = value;
}
}
This prevents you from having to type out the full property declaration. This is useful when you don't have any additional logic in the getter and/or setter.
If you're creating simple data mapping and transfer classes, auto-implementing properties can make the class definition far more concise.
When you see
public int Count { get; set; }
as a member of a class, that is not nothing. You're just deferring to the default implementation of auto-properties. It's roughly,
private int _count;
public int get__Count()
{
return _count;
}
public void set__Count(int value)
{
_count = value;
}
You just have syntactic sugar in C# to use these methods roughly like a field, i.e.
instanceOfObject.Count = 42; // Not a field access, but behind the scenes a method call.

How set value when the property has the getter method using reflection in c#

public class test
{
public test()
{
ting=10;
}
private int ting{get;set;}
public int tring
{
get
{
return ting;
}
}
}
void Main()
{
var t= new test();
//Below line giving error
Console.Write(t.GetType().GetProperty("tring").SetValue(t,20));
}
How to resolve this using reflection?
Well yes - the property can't be set. It's read-only, presumably deliberately.
If the designer of the class hasn't given you the opportunity of setting the value, you shouldn't be trying to set it. In many cases it would be impossible to do so, as the value may not even be backed by a field (think DateTime.Now) or may be computed some non-reversible way (as per Marcin's answer).
In this particular case if you were really devious you could get hold of the IL implementing tring.get, work out that it's fetching from the ting property, and then call that setter by reflection - but at that point you're going down a very dark path which you're almost certain to regret.
You can't do that, unless you know what is the backing field name. When you do, you can just set the field value, and it will reflect to property value.
Consider the situation when it would be possible and your property wouldn't be backed by a field (like that):
public string tring
{
get
{
return string.format("foo {0} foo", ting);
}
}
What should be desired output of setting that property?

What is the meaning of "get"? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In C# what does this code with “get” mean?
I'm using open source project. In this project there is function.
public virtual ICollection<Customer> AffiliatedCustomers
{
get
{
return _affiliatedCustomers ?? (_affiliatedCustomers = new List<Customer>());
}
protected set { _affiliatedCustomers = value; }
}
I don't understand what is the meaning of "get".
Can you please explain this function.
AffiliatedCustomers is a property.
The get defines the property getter, which is a method used internally to return the value by the property. It allows you to use this given an instance of the class like so:
var customers = theClass.AffiliatedCustomers; // Looks like a field, but is a property
Properties can also have a set section, as well, as this one does (protected set { _affiliatedCustomers = value; }), which gives you control over what happens when you set the value via the Property.
For details, see Properties in C#.
This is not a function. It is a property. A property is basically a fancy wrapper for some variable. For example, declaring the following property:
public string SomeProperty { get; set; }
will actually compile to something like this:
private string backing_SomeProperty;
public void set_SomeProperty(string value)
{
backing_SomeProperty = value;
}
public int get_SomeProperty()
{
return backing_SomeProperty;
}
That's an example of an automatic property. Of course, you can also define the getter and setter methods yourself like this:
public string SomeProperty
{
get
{
// some logic code here
// then return some value
}
set
{
// some logic code here
// then set some value
}
}
This is a property,
Quoted by msdn:
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.
Please refer to this link for more:
http://msdn.microsoft.com/en-us/library/x9fsa0sw(v=vs.80).aspx
Properties have a getter and a setter - their purpose is obvious (to get and set the value of the property).
When you use auto properties, there is still a get and a set, but the backing variable is automatically implemented for you. In the example you have given the author of the code has chosen to have their own implementation of the get - in this case to automatically initialise the member variable the first time the property is accessed.

c# what is the point of using SET?

why do we do this:
private string StatusText
{
set { toolStripStatusLabel1.Text = value; }
}
instead of just this?
private string StatusText
{
toolStripStatusLabel1.Text = value;
}
i do not understand the point of using set?
These are two completely different things.
This is a method:
private string StatusText()
{
toolStripStatusLabel1.Text = value;
}
which is called like this:
StatusText();
(and which will not compile, because the local variable value cannot be found). To make it work, you would need to write it like this:
private string StatusText(string value)
{
toolStripStatusLabel1.Text = value;
}
and call it like this:
StatusText("bla");
On the other hand, this is the definition of a property:
private string StatusText
{
set { toolStripStatusLabel1.Text = value; }
}
whose setter (hence the keyword set) is called like this:
StatusText = "bla";
Because there could also be a get:
get { return toolStripStatusLabel1.Text; }
Properties are syntactic sugar. When compiled you will have two methods get_[property name] and set_[property name]. If you only have the set method, only the set_[propety name] will be in the IL.
In a little more detail, since the OP has said she doesn't understand gets and sets:
The get and set keywords are used to define a "property". A property is a pair of methods - a "getter" and "setter" - that are used behind the scenes when the property is used or written to by other code. The advantage of a property over explicitly defining getter and setter methods is that you can use the property as if it were a "field" (a simple, publicly-visible member variable). The advantage of using a property instead of a field is that a property allows you to customize the behavior of assigning or using a variable. You can create "calculated fields" that are evaluated when needed based on other data in the object, or include basic validation or other business logic when reading or writing a value.
To define a property, you start by declaring it like you would a field, but then add a code block with get and set sub-blocks. You then define its read behavior in the get block, and the write behavior in the set block. You can choose to define only one accessor (making a "read-only" or "write-only" property), or you can define more limited visibility for one function or the other; for instance, you can make the getter public but the setter protected, so everyone can examine the property's value but only the class's other members and derived types can set its value.
The most common property implementation uses a "backing field", a private variable that acts as the store for the value exposed by the property. To streamline this implementation, .NET 3.0 included the concept of an "auto-property"; if you didn't define the code bodies of the getter and setter, the compiler would generate a basic implementation using a backing field.
First will not compile for value isn't valid unless you have set.
private string StatusText
{
toolStripStatusLabel1.Text = value;
}
Check out MSDN on Accessors here.
Setting and Getting fields and properties...
Example:
private string statusText;
public string StatusText
{
get { return this.statusText;}
set { this.statusText = value;
toolStripStatusLabel1.Text = this.statusText;
}
}
private String StatusText
{
get { ... }
set { ... }
}
The get/set tokens are to distinguish between the get and set accessors.
The latter wouldn't compile. The set part shows that it's the setter part of a property.
An alternative is to just write a method:
private void SetStatusText(string value)
{
toolStripStatusLabel1.Text = value;
}
To enable you to apply more complex logic, when the need will arise.

Categories

Resources