initialising strings

  • Thread starter Thread starter Bob
  • Start date Start date
B

Bob

Hi,
In the IDE is there any way to turn off the compiler warning about strings
being used before being initialised.
Given that a string is an immutable object why bother initialising it before
assigning a value to it?
Thanks
Bob
 
Bob said:
Hi,
In the IDE is there any way to turn off the compiler warning about strings
being used before being initialised.
Given that a string is an immutable object why bother initialising it
before
assigning a value to it?
Thanks
Bob

A string is immutable but a variable of type string is a reference to a
string and can be changed to a completely different (immutable) string:

string a = "immutable 1";
a = "immutable 2"; // OK
a[2] = 'z'; // error - immutable.

What you are thinking of is a "readonly" string.
 
Bob said:
In the IDE is there any way to turn off the compiler warning about strings
being used before being initialised.
Given that a string is an immutable object why bother initialising it before
assigning a value to it?

It sounds like you don't quite understand the error message properly.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

Then we can try to explain the message.
 
Hi Jon,
Good Call. I went back and re-examined the code and there was a path where a
string could have been used with a null value. I shall check the rest.
Thanks
Bob
 
Bob said:
Good Call. I went back and re-examined the code and there was a path where a
string could have been used with a null value. I shall check the rest.

Right - the problem isn't that it could have been used with a null
value. The problem is that local variables don't *have* a value
(logically at least) until they've been definitely assigned.
 
Back
Top