For a public primitive variable; is it possible to implement the set method and 'Short-Implement' the get method?
When I say 'Short-Implement' the get I mean:
public double width { get; set { width = (isLocked) ? 0:value; } }
Instead of 'Long-Implement' the get:
public double width { get { return width; } set { width = (isLocked) ? 0:value; } }
I get a compile error when I attempt to 'Short-Implement' the get (whats the term for this btw?) and 'Long-Implement' the set. The compile error is:
`Cube.width.get' must have a body because it is not marked abstract, extern, or partial
is it possible to implement the set method and 'Short-Implement' the get method?
No, auto-implemented properties do not allow you to define any part of the getter or setter's implementation.
From Auto-Implemented Properties (C# Programming Guide):
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors
Use a backing field, and consider treating code that calls your setter when isLocked is true as erroneous and throwing an exception.
set
{
if (isLocked)
throw new InvalidOperationException("Knock that set off!");
_width = value;
}
Related
This question already has answers here:
How to avoid stack overflow errors when defining set accessor in C#
(4 answers)
Closed 6 years ago.
I have an object with a property for which I want to create a custom setter and also keep the automatic getter:
public class SomeObject
{
public int SomeProp { get; set; }
public Nullable<short> MyProp
{
get
{
return MyProp;
}
set
{
if (value != null)
{
SomeProp = SomeWork(value);
MyProp = value;
}
}
}
}
The problem is that I get a Stackoverflow error on the getter. How do I implement a property where I keep the getter as it is but only modify the setter?
You need to use a backing field for your property. You're getting a SO error because you're recursively referencing your MyProp property in its own getter resulting in infinite recursion.
private short? _myProp;
public short? MyProp
{
get
{
return _myProp;
}
set
{
if (value != null)
{
SomeProp = SomeWork(value);
_myProp = value;
}
}
}
NO, it's not possible. Either you make it a complete auto property (OR) define both the getter and setter in which case you will have to provide the backing field since compiler won't create one for you.
You get the exception because you're essentially doing infinite recursion in your property.
Unfortunately what you're describing isn't possible in C# yet, you need to define the backing field yourself.
You cannot do that. You either use custom getter setters (both, not single) or you stick to auto getters.
In your code getter of your property is trying to access getter of itself (which is going to access the same getter and so on and so on)
So it's an endless loop which is going to destroy all the world and bring the end of humanity
public List<ObjectA> ObjectAList
{
get
{
return ObjectAList ?? new List<ObjectA>();
}
set;
}
'ObjectAList.set' must declare a body because it is not marked abstract, extern, or partial
Why is that?
You are trying to mix Auto implemented property with normal property. Moreover you need a backing field, otherwise you will run in to Stackoverflow exception. Your property declaration should be like:
private List<ObjectA> _ObjectAList; //private backing field
public List<ObjectA> ObjectAList
{
get
{
return _ObjectAList ?? new List<ObjectA>();
}
set
{
_ObjectAList = value;
}
}
Thats how the langauge works.
You cant do partial explicit / implicit.
Its all or nothing.
When you do it implicitly it just writes to an auto generated backing field, but it wants to do both sides.
Moreover your get is going to have a stack overflow even if the set worked because you are going to call the get over and over with no base case to end the recursion.
Why are we able to write
public int RetInt
{
get;set;
}
instead of
public int RetInt
{
get{return someInt;}set{someInt=value;}
}
What is the difference between the two?
This feature is called Auto implemented properties and introduced with C# 3.0
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.
class Customer
{
// Auto-Impl Properties for trivial get and set
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
For your question
What is the difference between the two?
In your case, none. Since you are not doing anything while setting or retrieving the value, but suppose you have want to do some validation or want to perform other types of check then :
private int someInt;
public int RetInt
{
get
{
if (someInt > 0)
return someInt;
else
return -1;
}
set { someInt = value; } // same kind of check /validation can be done here
}
The above can't be done with Auto implemented properties.
One other thing where you can see the difference is when initializing a custom class type property.
If you have list of MyClass
Then in case of Normal property, its backing field can be initialized/instantiated other than the constructor.
private List<MyClass> list = new List<MyClass>();
public List<MyClass> List
{
get { return list; }
set { list = value; }
}
In case of Auto implemented property,
public List<MyClass> SomeOtherList { get; set; }
You can only initialize SomeOtherList in constructor, you can't do that at Field level.
How are these two different ?
There are different at least by 2 points:
In normal property you have to define a field before (someInt in your case)
In normal property you can set a breakpoint into the set/get modifiers, instead in auto property can not do that.
In other words: if you need "just property", use auto-properties, if you need more control over workflow (raise an event on set, debug, run other stuff inside), use "normal" properties.
These are auto implemented properties. Please see http://msdn.microsoft.com/en-us/library/bb384054.aspx for more info.
Basic reason why these were introduced was to reduce the overhead of programmer of creating a private variable like someInt which had little use than being used in a property.
Actually these aren't really different, in both cases you have a private field that corresponds to your property, but in the first case it is generated by the compiler and hidden.
If you need to use the variable behind the property quite often in your class, I think it's better to declare your property the old way (2nd one), because each time you will access it this will call the getter if you do it the "new" way.
If you only need it to be used from outside your class (or in most of cases), then you can go with the "new" way (1st one)
Is there a way to do something like this in C#:
public class Class2 {
public string PropertyName1 { get
{
return this; //i mean "PropertyName1"
}
set {
this = value;
DoAdditionalFunction();
}
}
Because I need to call additional function in the "set" I need to have an extra private field like
private string _propertyName1;
public string PropertyName1 { get
{
return _propertyName1;
}
set {
_propertyName1= value;
DoAdditionalFunction();
}
I don't want to use additional property like _propertyName1. Is there a way to accomplish this or any best practices?
No - if you need any behaviour other than the most trivial "set a field, return the field value", you need to write "full" properties. Automatically implemented properties are only a shorthand for trivial properties.
Note that you haven't really got an "extra" private field, in terms of the actual contents of an object - it's just that you're explicitly declaring the private field instead of letting the compiler do it for you as part of the automatically implemented property.
(It's not clear what your first property is trying to do - setting this in a class is invalid, and you can't return this from a property of type string unless you've got a conversion to string...)
One of the nice features of .net is class Properties - wrapping gettter and setter of class field (which is private, but accessor methods are ussualy public). From outside of a class this Property looks as one field and does not flood intellisense with nomber of getters and setters.
Usual syntax is
private bool _isReadOnly;
public bool IsReadOnly
{
get { return _isReadOnly; }
set { _isReadOnly = value; }
}
or for implicit declaration it is
public bool IsReadOnly
{
get;
set;
}
This is very nice, both accessors can have even different access modifiers, eg. private setter.
My question is: does .NET support setters or getters with parameters? Like to have setter with two parameters - for example - one is value to set and other is bool which indicates something like "notify listeners about change" or "do not overwrite old value if newer value fails check" or something like that. Parameter for getter could be some option to format output or whether returned value should be clone of old etc.
Thank you. I do dot need it for any particular goal to achieve, so no need to post workarounds, i just wonder if there is something like this in .net Property.
VB.NET supports parameters on properties.
C# doesn't.
No - a property is simply used to retrieve or set a value. For your examples, you'd need to use a method.
c# DOES NOT support setters or getters with parameters.
Nope; however, you can make the get/set accessors have some nice check logic. If you have another field that you set (outside of the get/set) method, you can check against that field during your 'set' update to branch your logic based on a condition.
private bool positiveOnly;
private int _myNum;
public int MyNum
{
get {return _myNum;}
set
{
// use old if positive only and value less than 0
_myNum = (positiveOnly && value < 0) ? _myNum : value;
}
}
public void MyMethod()
{
positiveOnly = true;
MyNum = Convert.ToInt32(txtMyTextBox.Text);
}