Search code examples
c#exceptionstack-overflow

Bad Class with StackOverflowException What is C# doing


When I call the constructor, the program gets a StackOverflowException.

public class User{
    public User(string email, string pass){
        this.email = email;
        this.pass = pass; 
    }
    public string email{
        get => email;
        set => email = email;
    }
    public string pass{
        get => pass;
        set => pass = pass;
    }
}

Process is terminating due to StackOverflowException.


Solution

  • This makes infinite loop

    this.email = email
    

    How to fix

    public class User{
        public string e;
        public string p;
        public User(string email, string pass){
            this.e= email;
            this.p= pass; 
        }
    }
    

    With properties

    public class User{
         public string e;
         public string p;
         public User(string email, string pass){
         this.e= email;
         this.p= pass; 
         }
         public string Pass{
    
                get { return this.p; }
    
                set { this.p= value; }
    
         }
         public string Email{
    
                get { return this.e; }
    
                set { this.e= value; }
    
         }
     }