static bool firstTime = true

  • Thread starter Thread starter Brahm
  • Start date Start date
B

Brahm

Hello,
I am trying to do this in C# within a private void method but the value
keeps changing in each call. I tried to use const but i get compiler
errors.

const bool firstTime = true;
if( firstTime == true)
{
firstTime = false; // compiler does not like this
}

I get left hand side of an assignment must be a variable.
Thanks, Please tell me how to reply...
BRAHM
 
Brahm said:
Hello,
I am trying to do this in C# within a private void method but the value
keeps changing in each call. I tried to use const but i get compiler
errors.

const bool firstTime = true;
if( firstTime == true)
{
firstTime = false; // compiler does not like this
}

C# does not support local static variables (a la C and VB).

Use a private member variable instead.

David
 
Hi,

It's not clear what you want to do as you do not provide code.
A few hints only
A static variable cannot be declared inside a method

I assume you are coming from C++ ( or C to be more exact ) , what you do in
this case is declare a member variable, it will exist between calls to the
method which is your intended objective.

a const cannot be changed, it cannot appear in the left side of an
assignation. that's why you are getting that error.

You should not use static UNLESS you want that the value of it to persist
during the run of the application, and across all the instances of that
type.


Please post back if you still have doubt about this.


Cheers,
 
David,
Thanks for your reply. So, i need to have a private variable in my
class initialized to "true". So, the method needs to check it like
this._variablename and if it is true, it does the one thing and sets it
to false so the next time the function is called, an alternative logic
is executed. ok, this should work.
Then const means constant and it is not supposed to change and readonly
means it is not supposed to change except the creator of the object...

Thanks, again.
BRAHM
 
Then const means constant and it is not supposed to change

Yes, as the name "constant" implies......

Also, when checking for a boolean variable to be true, you don't need
to compare it to "true" - just check the variable itself, it's ALREADY
a boolean! (which is only true or false anyway):

if(firstTime)
{
firstTime = false;
}

Marc
================================================================
Marc Scheuner May The Source Be With You!
Bern, Switzerland m.scheuner(at)inova.ch
 
Back
Top