How to handle uninitialized local variables

After reading this Eric Lippert Article, I understand that the C # compiler does not like it if you leave the local variables uninitialized.

When I came across this “problem” from time to time, I looked at some of my old code and was able to filter out most of the situation where uninitialized ( SomeClass obj = null) local variables are not really needed .

But I came up with a situation where I do not know how to reorganize the code.

public void DoSomething(string foo) {   

    SomeClass obj; // = null; 

    try {
        obj = SomeClass.CreateItem(target);
    } catch(CustomException ex) {
        // notify UI of error
    }

    if (obj != null) {
        // do something with `obj`
    }
}

SomeClass.CreateItemmay fail due to external factors. If so, I want to notify the user if I do not want to perform the action.

The C # compiler does not want me to leave objuninitialized, so I usually assign it to it null.

"", :

?

, , , ?

+4
3

:

private SomeClass TryToCreateItem()
{
    try 
    {
        return SomeClass.CreateItem(target);
    } 
    catch(CustomException ex) 
    {
        // notify UI of error
    }
    return null;
}

public void DoSomething(string foo) 
{ 
    SomeClass obj = TryToCreateItem(); 
    if (obj != null) {
      // do something with `obj`
    }

" " - .

+9

// do something with obj`` try.

, , , , , . , , , , , . , , , , , try.

+2

, try/catch, , - , , bool, :

    public void DoSomething(string foo)
    {

        bool failedCreation = false;

        try
        {
            SomeClass obj = SomeClass.CreateItem(target);
        }
        catch (CustomException ex)
        {
            // notify UI of error
            failedCreation = true;
        }

        if (failedCreation)
        {
            // do other stuff.
        }
    }

, . try/catch .

0

All Articles