Reputation: 3318
So im trying to use the get / set properties on C# but I cant get my code to work ( it crashes my console app )
This is my textHandler.cs file as you can see the public static void method WriteInfo is using get / set properties but it crashes my app..
class TextHandler
{
public static void WriteInfo(String text)
{
var consoleText = new Text();
consoleText.text = text;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(consoleText);
Console.ForegroundColor = ConsoleColor.White;
}
public static void WriteError(String text)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(text);
Console.ForegroundColor = ConsoleColor.White;
}
public static void WriteSuccess(String text)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(text);
Console.ForegroundColor = ConsoleColor.White;
}
public static void WriteText(String text, ConsoleColor color)
{
}
}
public class Text
{
public String text
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
}
Here I call that method
TextHandler.WriteInfo("New client with version : " + message + " | current version : " + version);
If I remove that line the app doesnt crash anymore, dont know what Im doing wrong since I dont get any error. Also if this is a bad method to do this please tell me I would like to improve Thanks
Upvotes: 0
Views: 6066
Reputation: 640
So, You are setting the into the property that is calling again the set method until you get a StackOverflow exception.
To avoid this try this
public class Text
{
string _text = null;
public String text
{
get
{
return this.text;
}
set
{
_text = value;
}
}
}
Or empty get set methods
public class Text
{
public string text { get; set; }
}
Upvotes: 1
Reputation: 67296
You need to separate the "backing" field from the public property:
public class Text
{
private string text;
public String TheText
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
}
In the above example, TheText
is the a "badly named" public property and text
is the backing field. At the moment, your code is addressing the same field for both, causing recursion. Usually the convention would be to have a capital property Text
and a lowercase backing field text
.
However, in your code you have named the class Text
so it is confusing to address text.Text
.
Upvotes: 4
Reputation: 992
There is no need to create the "Text" class. Just pass the string to Console.WriteLine. Also, you didn't specify the nature of the application. This will work fine in a console app, but may not work for a web application or other app that is not bound to the SdtOut
Upvotes: 1
Reputation: 62248
The code that creates infinit recursion is:
public String text
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
In set you assign this.text = value
to itself, creating infinit recursion, so StackOverflow
soon or later.
Seems that you do no need a field, so change your code to:
public String Text {get;set} //PROPERTIES ARE UPPERCASE BY MS STANDART
Upvotes: 6