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);
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).
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."
#pragma warning disable 0168
catch (ChangeConflictException x)
{
// code here
}
#pragma warning enable 0168
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