jitender singh
jitender singh

Reputation: 57

how to avoid stack overflow exception in this code?

I got StackOverflowException in my code

 public int Movie_ID
 {
     set
     {
         if (value == 0)
         {
             throw new Exception("value cannot be empty");
         }

         Movie_ID = value;
     }
     get
     {
         return Movie_ID;
     }
 }

Exception of type 'System.StackOverflowException' was thrown."}

Upvotes: 2

Views: 66

Answers (1)

Owen Pauling
Owen Pauling

Reputation: 11841

Your get keeps calling itself recursively. You need to create a backing field and return that value, not call the property again. e.g:

private int _movieId;

public int Movie_ID
 {
     set
     {
         if (value == 0)
         {
             throw new Exception("value cannot be empty");
         }

         _movieId = value;
     }
     get
     {
         return _movieId;
     }
 }

Upvotes: 6

Related Questions