Skip to content

"Use of unassigned local variable" CS0165 issue #4272

@michmela44

Description

@michmela44

I'm getting a complaint in my code using VS 2015 and .Net 4.5.2, and am not quite understanding why.

If I call

MyObject o;
if (objects != null && objects.TryGetValue(objectName, out o))
    v.Property= o;

then everything is fine. The following two cases however give me an error, and I'm not quite understanding why.

MyObject o;
if (objects != null ? objects.TryGetValue(objectName, out o) : false)
    v.Property= o; // <-- error CS0165: Use of Unassigned local variable 'o'

and

MyObject o;
bool b;
if (objects != null)
    b = objects.TryGetValue(objectName, out o);
else
    b = false;
if (b)
    v.Property = o; // <-- error CS0165: Use of Unassigned local variable 'o'

In either of the last 2 cases, I don't see how o can be used unless TryGetValue is called, which means o should be initialized.

Is this a bug? Or I am I missing something?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions