This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
New to C#, why does Property Set throw StackOverflow exception?
I'm getting a stack overflow exception when I try to set a static property.
public static class StaticTest
{
static string stringToSet
{
get
{
return stringToSet;
}
set
{
stringToSet = value;
}
}
}
Then, in other class:
public void setStaticProperty()
{
StaticTest.stringToSet = "Hello World"; // StackOverflow exception here
}
What I'm doing wrong?
set
{
stringToSet = value;
}
You got infinite recursion in your setter (and getter for that matter) since it calls itself, hence StackOverflow.
If you don't need to modify the underlying field directly, use an auto-property instead:
static string stringToSet {get; set;}
In your static property setter, you are assigning a value to the static property stringToSet, which calls your static property setter, where you are assigning a value to the static property stringToSet, which calls your static property setter, where you are assigning a value to the static property stringToSet, which calls your static property setter, where you are assigning a value to the static property stringToSet ...
You need to add a private field to store the property value; usually you'd then rename the property to start with a capital letter (StringToSet).
private string stringToSet;
public string StringToSet {
get {
return stringToSet;
}
set {
stringToSet = 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
This question already has answers here:
c#: getter/setter
(9 answers)
Closed 7 years ago.
I'm trying to learn C#, and am coming from Java. I've seen this in C#:
class A {
public string x { get; set; }
}
What do I do if I want to intercept the incoming value on the setter?
This is just syntactic sugar for
private string x;
public string X
{
get { return this.x; }
set { this.x = value; }
}
which is effectively what the compiler really outputs for your code, though you can't access the field x directly.
Always use this long form if you need to do anything beyond setting and retrieving the value from a field.
You can create a backing store:
private string _x;
public string x {
get {
return _x;
}
set {
// do something - you can even return, if you don't want the value to be stored
// this will store the value
_x = value;
// do something else
}
}
First you should make a private property that you will store the actual values in. In the get function just return that private property. In the set method you can use the value keyword to see the incoming value and do whatever you want before actually setting the private property;
public class A
{
private string xPrivate;
public string X {
get { return this.xPrivate; }
set { this.xPrivate = value; }}
}
I am asking a beginner level question. Though I am working in MVC but I am really confused with a simple concept and that is "Properties". There are lot of questions that
I have already gone through but there is surely a doubt in mind and did'nt able to clear it up.
Actually c# properties used for getting and setting the value to the private fields.
Like
Public class MyClass
{
private int number;
public int Number{
get{ return this.number;}
set{ number=Value }
}
}
class Program
{
static void Main()
{
MyClass example = new MyClass();
example.Number = 5; // set { }
Console.WriteLine(example.Number); // get { }
}
}
Now , the value is assigned to property also and to the variable also. Right?
Now , here is my doubt::
When we create property in model for MVc structure, we only have
public int Number{get;set;}
If this is okay to work with then why we are creating unnecessorily one more field of private access specifier. If encapsulation is the reason for that or hiding the data then why not in model in MVC?
Actually, in the above class example can I only use
Console.WriteLine(example.number);
after declaring it public?
Then what's the use of creating property over here?
Properties can be used to a store and retrieve values from a backing field (number in your case) directly as in your first sample. But property getters and setters are ordinary blocks of code that you can use as you want. So you don't have to assign a backing field, but can derive the value of a property also from another property in a getter, e.g.
public int NumberTimesTwo
{
get
{
return Number * 2;
}
}
However, as a common scenario is to have a property retrieve and assign the value of a backing field, there is a shortcut that you can use:
public int Number { get; set; }
In this case, the compiler automatically creates a private backing field that the property retrieves in the getter and assigns in the setter, so the code is equivalent to the following, but less to type:
private int _number;
public into Number
{
get
{
return _number;
}
set
{
_number = value;
}
}
As the backing field is also private, you cannot access it from outside of the class directly.
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
You are implementing Encapsulation by using MyProperty, which is public to access myVar which is private and is accessible only in the block where defined, that is, your class and not outside it.
Btw, in what way does this QA not answer your question? Try going through this for further reference.
Do I need to declare a class-level variable to hold a property, or can I just refer to self.{propertyname} in the getter/setter?
In other words, can I do this? (where I haven't defined mongoFormId anywhere):
public string mongoFormId
{
get
{
return this.mongoFormId;
}
set
{
this.mongoFormId = value;
revalidateTransformation();
}
}
You can either use automatic accessors or implement your own. If you use automatic accessors, the C# compiler will generate a backing field for you, but if you implement your own you must manually provide a backing field (or handle the value some other way).
private string _mongoFormId;
public string mongoFormId
{
get { return this._mongoFormId; }
set
{
this._mongoFormId = value;
revalidateTransformation();
}
}
UPDATE: Since this question was asked, C# 6.0 has been released. However, even with the new syntax options, there is still no way to provide a custom setter body without the need to explicitly declare a backing field.
You need to set a field variable and store the value there, if you're going to use custom getter and setter.
With the code you have right now you will be running into a stack overflow exception. When you assign something to mongoFormId, you'll execute the line this.MongoFormId = value;. This is an assignment to mongoFormId, resulting in executing the line this.MongoFormId = value;, and so on. It won't ever stop.
The correct way is a field:
private string _mongoFormId;
public string mongoFormId {
get { return this._mongoFormId; }
set {
this._mongoFormId = value;
revalidateTransformation();
}
}
You should have a backing variable. Take a closer look:
get { return this.mongoFormId; }
Is going to call the getter on mongoFormId, which will call that code again, and again, and again! Defining a backing variable will avoid the infinite recursive call.
Check MSDN Properties Overview
While a property definition generally includes a private data member,
this is not required. The get accessor could return a value without
accessing a private data member. One example is a property whose get
method returns the system time. Properties enable data hiding, the
accessor methods hide the implementation of the property.
You can do it both the ways.
If you want to have a class level member variable then do it this way -
public class sampleClass
{
private string _mongoFormId;
public string mongoFormId {
get { return _mongoFormId; }
set {
_mongoFormId = value;
revalidateTransformation();
}
}
}
Or do this simple in class, if no need for revalidateTransformation() execution call there
public class sampleClass
{
public string mongoFormId {get; set;}
}
This won't work since you get a recursive call to the property.
If I'm not mistaken, the result will be a StackOverflowException.
You must use a variable.
private string mongoFormId;
public string MongoFormId
{
get
{
return this.mongoFormId;
}
set
{
this.mongoFormId = value;
revalidateTransformation();
}
}
If you don't have to execute revalidateTransformation, you can use the auto-property.
This will create a backingfiled for you behind the scene.
public string MongoFormId { get; set; }
With the code you wrote, you are creating a recursive endless loop on both the get and set. The this keyword refer to the current class, not the property you are in.
So yes, you need to declare a private field. And to avoid confusion, create properties following the MSDN Naming Guideline (Use Pascal case for properties, camel case for private fields). And please do the same for your methods, it should be RevalidateTransformation instead of revalidateTransformation if you follow the C# convention instead of java's.
private string mongoFormId;
public string MongoFormId
{
get
{
return mongoFormId;
}
set
{
mongoFormId = value;
RevalidateTransformation();
}
}
public string mongoFormId {
get {
return this.mongoFormId;
}
set {
this.mongoFormId = value;
revalidateTransformation();
}
}
this way you have the Function recursive on all paths
The only way i see is to use a private data member. As other boys tells.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
default value for a static property
I am able to assign default value for a normal default property of a class.
But i am not able to assign default value for a static default property of a class like below:-
public class AppInstance
{
[DefaultValue(25)]
public static int AppType { get; set; }
}
When I call AppInstance.AppType, it always return 0 instead of 25. Why? How can i solve it without using a private variable declaration?
The DefaultValueAttribute only tells the WinForms designer which value is the default value of a property of the form or of a control. If the property has another value, this value will appear bold in the properties window. But it will actually not set the value.
You must assign it a value in the static constructor
static MyClass()
{
AppType = 25;
}
You can use a static constructor. It is called automatically to initialize the class before the first instance is created or any static members are referenced.
public class AppInstance
{
public static int AppType { get; set; }
static AppInstance()
{
AppType = 25;
}
}
I don't see the use for an static member to be created by using get; set; in this scenario. Maybe somebody else can?
So, I would probably just do this:
public class AppInstance
{
public static int AppType = 25;
}