I have a problem when use recursive method call.
I know the problem here setInfo(ref name, ref age, ref address, ref country);, but I don't know how to fix it.
class person{
private string name;
private short age;
private string address;
private string country;
public person(){
Console.Write("Hi i'm constructor \n\n");
}
public void setInfo(ref string name, ref short age, ref string address, ref string country){
if (name != "" || address != "" || country != "" || age != 0) {
this.name = name;
this.age = age;
this.address = address;
this.country = country;
} else {
setInfo(ref name, ref age, ref address, ref country); // Here is what I doubt.
}
}
public void getInfo(){
Console.Clear();
Console.WriteLine("---- The information ----\nName: {0}\nAge: {1}\nAddress: {2}\nCountry: {3}", this.name, this.age, this.address, this.country);
}
}
// When usage
static void Main(string[] args){
string name, address, country;
short age;
person one = new person();
Console.Write("Name: ");
name = Console.ReadLine();
Console.Write("Age: ");
Int16.TryParse(Console.ReadLine(), out age);
Console.Write("Address: ");
address = Console.ReadLine();
Console.Write("Country: ");
country = Console.ReadLine();
one.setInfo(ref name, ref age, ref address, ref country);
one.getInfo();
}
elseit will never leave the recursive call since you don't change any values there.refkeyword for passing parameters. All objects in C# (includingString) are reference types and are passed around by reference. Using therefkeyword in C# is rather unusual and indicates design issues in most cases. And since you know you have a recursive call, why not remove it? What did you intend to do with this call anyway?