Using property gets me into infinite loop

C

Curious

Hi,

I have a C# class that contains a property defined as follows:

public bool bRunTwice
{
get { return bRunTwice; }
set { bRunTwice = value; }
}

Then I have a method in the same class that uses the property as
below:

bRunTwice = true;

This causes an infinite loop. However, if I replaced the property
block to a public member (which is not the best way):

public bool bRunTwice;

Everything works. How come using property causes trouble?
 
V

VJ

your property variable and and Property name are same..

How did the first complie for you? It won't work, same variable name in
class !!

VJ
 
V

VJ

Oh yes.. I just ran a test... you can just do the below..without declaring a
private variable bRunTwice.
public bool bRunTwice
{
get { return bRunTwice; }
set { bRunTwice = value; }
}


It complies... yicky... :)

Anyway curious.. please keep the private variable and Property name
different.

VJ
 
C

Curious

your property variable and and Property name are same..

How did the first complie for you? It won't work, same variable name in
class !!

VJ

Since it's a property, it's not a private member. I just use it like
follows:

bSkipFirstPageInReview = true; //This calls set { bRunTwice =
value; } infinite number of times. Why?


It compiles.
 
C

Curious

Since it's a public property, it's not a private member. I use it the
way follows:

bRunTwice = true; //This calls set { bRunTwice =
value; } infinite number of times. Why?

BTW, it compiles fine.
 
B

Barry Kelly

Curious said:
Since it's a property, it's not a private member.

Whether a member is a property or not is orthogonal to its visibility.
Private properties are perfectly valid.
I just use it like
follows:

Properties don't have any storage. They are simply syntactic sugar for
one or two methods. Your definition in your original post goes into an
infinite loop because it recursively calls the getter in the getter, and
the setter in the setter.

The standard pattern for most properties is to have a private field on
the class, and the property reads from and writes to the field. E.g.:

class T
{
int _myField;

int MyField
{
get { return _myField; }
set { _myField = value; }
}
}

-- Barry
 
C

Curious

Hi Barry,

What you suggest sounds right to me. Let me try it and let you know.
Many thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top