Search code examples
c#.netdeclaration

Use of local unassigned variable - even with else-statement


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?


Solution

  • 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;