-4
MediaDescription media;
foreach(var field in fields) {
    switch(field.Key) {
        case FieldType.Version:
            message.Version = Convert.ToInt32(field.Value);     
            break;
        case FieldType.Originator:
            message.Originator = OriginatorField.Parse(field.Value);
            break;
        ...
        ...
        case FieldType.Information:
            if(media == null)    <-- Use of local unassigned variable
                message.Description = field.Value;
            else media.Description = field.Value;
            break;
        ...

I mean, why? The compiler should be smart enough to that I precheck the declaration and that only in the else-statement the declaration gets accessed. What's wrong?

Atrotygma
  • 1,133
  • 3
  • 17
  • 31
  • 1
    "The compiler should be smart enough" is often a misguided argument. The compiler knows some things, it doesn't know other things. The fact is, writing a language and a compiler for it is *hard*. And when writing one, often the designers don't ask "why don't we do X?" but instead ask "is there a compelling reason why we *should* do X, given how hard it will be?" There could be lots of reasons why they didn't add this feature, and very few reasons why they would have added it. At its simplest, does the error persist if you declare the variable as `MediaDescription media = null;`? – David Jul 25 '13 at 15:18
  • Possible duplicate - http://stackoverflow.com/q/9233000/1324033 – Sayse Jul 25 '13 at 15:19

2 Answers2

1

Being not assigned and being assigned with null are two different states of a local variable. Local variables have to be initialized with something, even null, before they can be accessed. Be default they are not initialized at all, unlike class fields.

For comparison, this code does not give a compilation error:

MediaDescription media = null;
...    
    case FieldType.Information:
        if(media == null)    <-- Use of local unassigned variable
            message.Description = field.Value;
Andrei
  • 55,890
  • 9
  • 87
  • 108
  • Oooh, I did not know that. Assign with null works, altough it strange because assigned as well as unassigned variables are null. :/ – Atrotygma Jul 25 '13 at 15:23
  • 1
    @Atrotygma, actually unassigned local variables are not null. They are just, well, unassigned. – Andrei Jul 25 '13 at 15:23
1

I think you misunderstood compiler's message: the complaint is not that you may be accessing properties of the media object, but that you are accessing the variable itself, which does not hold a reference to any object at all - not even a null reference.

In C# local variables are not default-initialized - you must explicitly assign them during or after their initialization before the first use; even comparing them to null is not permitted.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523