2

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."}

3
  • public int MovieID { set { value = r1.Next(1, 10); MovieID = value; } get { return MovieID; } } Commented May 31, 2019 at 10:08
  • By using a backing field, for example. Commented May 31, 2019 at 10:10
  • 1
    return Movie_ID; calls Movie_ID; which calls (via property) return Movie_ID; etc. Commented May 31, 2019 at 10:11

1 Answer 1

6

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;
     }
 }
Sign up to request clarification or add additional context in comments.

2 Comments

side note: throw new Exception("value cannot be empty"); is evil; throw new ArgumentOutOfRangeException(nameof(value), "...") or alike
And if you are checking the value anyway, is negative allowed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.