c# - StackOverFlowException when setting property -
this question has answer here:
i'm trying using conditional statement check if value equals prior setting using setter
. returned stackoverflowexception error. using .cs file execute code general practice.
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; namespace job_classes { class workers { public string name { { return name; } set { if (name.compareto("admin") == 0 || name.compareto("admin") == -1) //just trying out comparison input. { console.writeline("invalid name."); //to see if invalid input not "admin" fails. } else { name = value; console.writeline("done."); } } } public workers() { this.name = null; } public workers(string name) { this.name = name; } public string information() { return string.format("name: {0}", name); } } }
my execution code in .cs is:
workers test = new workers("john");
the problem re-assigning within same property
causes recursion:
public string name { { return name; } set { if (name.compareto("admin") == 0 || name.compareto("admin") == -1) //just trying out comparison input. { console.writeline("invalid name."); //to see if invalid input not "admin" fails. } else { name = value; //stackoverflow here console.writeline("done."); } } }
if validating it, might wanna try different approach.
solution #1 (using separate variable name
property)
private string name = ""; public string name { { return name; } set { if (value != null) //check null before validation (or it's how handle null value) { if (value.compareto("admin") == 0 || value.compareto("admin") == -1) //just trying out comparison input. { console.writeline("invalid name."); //to see if invalid input not "admin" fails. } else { name = value; console.writeline("done."); } } } }
solution #2 (making set
private , using separate setter
method.
public string name { get; private set; //making private means can still //access setter within class via `this.name =` (so careful) } /// <summary> /// defined public setter can invoked outside /// </summary> /// <param name="value"></param> public void setname(string value) { if (value != null) //check null before validation (or it's how handle null value) { if (value.compareto("admin") == 0 || value.compareto("admin") == -1) //just trying out comparison input. { console.writeline("invalid name."); //to see if invalid input not "admin" fails. } else { name = value; console.writeline("done."); } } } public workers(string name) { this.setname(name); //be careful making this.name = name or else no validation } public workers() { this.setname(null); //be careful this.name = null or else no validation }
the disadvantage of second approach inside class workers
should careful when setting this.name
because still accessible inside workers
when set private
.
Comments
Post a Comment