Jojo Julian
Jojo Julian

Reputation: 1

How to return a class from a property get

I have this simple class property which should return a MyGuest class based on Guest. When I run the code using debugger in step mode, execution is looping betwen line 5 and 6.

Any suggestion would be highly appreciated.

1.    public Guest MyGuest
2.    {
3.        get
4.        {
5.            MyGuest = new Guest();
6.            return MyGuest;
7.        }
8.       set { }
9.    }

Upvotes: 0

Views: 59

Answers (1)

Richard Schneider
Richard Schneider

Reputation: 35477

Its a recursive loop because line 6 is calling 3 to get the value again. You want:

public Guest MyGuest { get { return new Guest(); } }

But do you really want to return a new Guest when the method is called?

Upvotes: 2

Related Questions