tags:

views:

142

answers:

2

Ok, so I have this nifty bit of code from Microsoft, and I have a little hiccup that I want to get rid of.

The original code prints out the ChangeConflictException x on the console, but I erased this line. Now, every time I use this bit of code, I get the error: "Variable 'x' is declared but never used".

What is the most efficient way to get rid of this error while retaining the functionality of the code?

//See http://msdn.microsoft.com/en-us/library/bb386918.aspx
try
{
    DB.SubmitChanges(ConflictMode.ContinueOnConflict);
}

catch (ChangeConflictException x)
{
    foreach (ObjectChangeConflict occ in DB.ChangeConflicts)
    {
        occ.Resolve(RefreshMode.KeepChanges);
    }
}
// Submit succeeds on second try.
DB.SubmitChanges(ConflictMode.FailOnFirstConflict);
+16  A: 

The compiler is right; it could just as well be:

catch (ChangeConflictException)
{
    foreach (ObjectChangeConflict occ in DB.ChangeConflicts)
    {
        occ.Resolve(RefreshMode.KeepChanges);
    }
}

which limits the exceptions which enter that block, but does not declare a variable for it. The variable is useful if you want to inspect the value, log it, or wrap it in another exception. Just for completeness (doesn't apply here) generally a re-throw should be throw;, not throw x; (to preserve the stack-trace).

Marc Gravell
Ok, I suspected you could remove the 'x', but the code is too complex for me to tell if it made any significant change.Thanks!
Soo
+1  A: 

Though in this case you can simply get rid of 'x' variable (as mentioned by Marc). Generally, for scenarios where i have these warnings and i can not change the code (like using some fields by reflection) i generally prefer making a do nothing call to conditional compilation method which suppresses such annoying warnings.

Code below.

    catch (ChangeConflictException x)
    {
    DoNothingWith(x);// This suppress the 'x' not used warning
    foreach (ObjectChangeConflict occ in DB.ChangeConflicts)
    {
        occ.Resolve(RefreshMode.KeepChanges);
    }
    }

    [Conditional("Debug")]
    public static void DoNothingWith(object obj){

    }

Reference from MSDN about Conditional attribute: "Calls to a conditional method are either included or omitted depending on whether this symbol is defined at the point of the call. If the symbol is defined, the call is included; otherwise, the call (including evaluation of the parameters of the call) is omitted."

Amby
You could also do this: `x = x`.
Loadmaster
@Loadmaster: Kindly explain to the class how getting rid of an "unused local" warning by replacing it with a "local is assigned to itself" warning is an improvement.
Eric Lippert
Um, okay, I didn't think the compiler would catch that.
Loadmaster