declaring a viarable

  • Thread starter Thread starter Robert Blackwell
  • Start date Start date
R

Robert Blackwell

If you define a variable when you declare it, does that mean that you can
never change the variable?
int myVar = 5;

Where as maybe
int myVar;
myVar = 5;

and later on somewhere I could then say
myVar =6;
?

Does that make sense.
 
Robert,

no, you are free to change the variable no matter how you declare it.

Only a variable declared as a const cannot be changed, e.g.

const int myVar = 5; // this cannot be changed

Also, have a look at the keyword 'static' in the documentation.

Steven.
 
Steven Wood said:
Robert,

no, you are free to change the variable no matter how you declare it.

Only a variable declared as a const cannot be changed, e.g.

const int myVar = 5; // this cannot be changed

Also, have a look at the keyword 'static' in the documentation.

Steven, I'm sure you know what static means... but mentioning it here could
be confusing.

For Robert, static has nothing to do with being able to change or not change
a variable. It simply means that a variable (or method or whatever element
it modifies) belongs to a particular instance of a class or is shared
between all objects. Sometimes I think the word "shared" in VB.NET makes
more sense.

But since static is sometimes confused with const by beginners, it is a good
idea to look up both and make sure you understand these keywords as you're
learning the language. I'd suggest readonly too, while you are at it.

Here's the full list of keywords for C#:

http://msdn.microsoft.com/library/d...y/en-us/csref/html/vclrfCSharpKeywords_PG.asp
 
Back
Top