After reading this Eric Lippert Article, I understand that the C# compiler doesn't like it if we leave local variables uninitialized.
As I encounter this 'problem' from time to time, I looked at some of my old code and was able to weed out most of the situation where actually don't need uninitialized (SomeClass obj = null) local variables.
But I came up with a situation where I don't know how to refactor 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.CreateItem may fail due to external factors. If it does, I want to notify the user, if not I want to perform an Action.
The C# compiler doesn't want me to leave obj uninitialized, so I usually assign null to it.
This feels like a 'hack' now and my question is:
Is there a design flaw in the code above?
And if there is, how should I deal with references at compile time, when I can't determine if they are going to point to an existing object at run time?
I would refactor the code like this:
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`
    }
"Extract method" is my favourite refactoring.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With