Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable 'x' is declared but never used error

Tags:

c#

linq

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);
like image 332
sooprise Avatar asked Jun 29 '10 20:06

sooprise


3 Answers

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).

like image 152
Marc Gravell Avatar answered Oct 10 '22 02:10

Marc Gravell


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."

like image 20
Manish Basantani Avatar answered Oct 10 '22 01:10

Manish Basantani


#pragma warning disable 0168

catch (ChangeConflictException x)
{
   // code here
}

#pragma warning enable 0168
like image 20
Scoobie Williams Avatar answered Oct 10 '22 03:10

Scoobie Williams