Debug.Assert-s use the same error message. Should I promote it to a static variable?

Posted by Hamish Grubijan on Stack Overflow See other posts from Stack Overflow or by Hamish Grubijan
Published on 2010-06-11T22:47:14Z Indexed on 2010/06/11 23:02 UTC
Read the original article Hit count: 188

Filed under:
|
|
|

I love Asserts and code readability but not code duplication, and in several places I use a Debug.Assert which checks for the same condition like so:

Debug.Assert(kosherBaconList.SelectedIndex != -1, "An error message along the lines - you should not ever be able to click on edit button without selecting a kosher bacon first.");

This is in response to an actual bug, although the actual list does not contain kosher bacon. Anyhow, I can think of two approaches:

private static readonly mustSelectKosherBaconBeforeEditAssertMessage = 
    "An error message along the lines - you should not ever be able to " +
    "click on edit button without selecting a something first.";
...
Debug.Assert(
    kosherBaconList.SelectedIndex != -1, 
    mustSelectKosherBaconBeforeEditAssertMessage)

or:

if (kosherBaconList.SelectedIndex == -1)
{
    AssertMustSelectKosherBaconBeforeEdit();
}
...
[Conditional("DEBUG")]
private void AssertMustSelectKosherBaconBeforeEdit()
{
    // Compiler will optimize away this variable.
    string errorMessage = 
        "An error message along the lines - you should not ever be able to " +
        "click on edit button without selecting a something first.";

    Debug.Assert(false, errorMessage);
}

or is there a third way which sucks less than either one above? Please share. General helpful relevant tips are also welcome.

© Stack Overflow or respective owner

Related posts about c#

Related posts about error-message