Lonzo
Lonzo

Reputation: 2818

How and where are you using Assertions in your c# code?

I need to know examples of how and where you are using assertions in c#.

EDITI need practical examples of where its most appropriate to use assertions. Thats why I need examples from those who have used them

Upvotes: 2

Views: 2862

Answers (9)

Chris Bennet
Chris Bennet

Reputation: 617

I used Debug.Assert() quite a bit in code that should never receive a bad/invalid parameter - the kind of code where the input parameters and dependant variables should have already been validated. Truth is, I know I'm going to make mistakes. I just don't know where. :-) Judicous use of "Debug.Assert" helps me cope with my imperfections.

Here's an example from my own code:

    public bool AddPoint(uint time, object value)
    {
        bool success = false;
        int index = 0;

        Debug.Assert(_selectedParameterName != null, "RecipeBusinessObject.InsertPointAtTime() _selectedParameterName = null");
        Debug.Assert(_currentRecipe != null, "RecipeBusinessObject.InsertPointAtTime() _currentRecipe = null");          
        Debug.Assert(CurrentParameterTable != null, "RecipeBusinessObject.InsertPointAtTime() CurrentParameterTable = null");

        Debug.Assert(index >= 0, "RecipeBusinessObject.InsertPoint(), index out of range, index = " + index.ToString());
        Debug.Assert(index <= CurrentParameterTable.Rows.Count, "RecipeBusinessObject.InsertPoint(), index out of range, index = " + index.ToString());

        DataRow newRow = CurrentParameterTable.NewRow();

        <snip>

Upvotes: 0

Richard
Richard

Reputation: 108985

There are different views (see recent sub-thread in comp.lang.c++.moderated, subject "We do not use C++ exceptions").

I take the view that assertions are best to check and document things that you know cannot be false, unless the implementation is inconsistent. This is stronger than pre-conditions and invariants.

E.g. that a helper function, which can only be called from a couple of different places, has a resource available. Because this helper is private and only used inside one class throwing an ArgumentException is not appropriate (that's for the public/protected interface).

Upvotes: 0

Mendelt
Mendelt

Reputation: 37483

I often use Debug.Assert for checking preconditions for my code. If an object depends on another object being present I might assert this other object is not null for example. This makes lots of problems visible even before I hand my programs to testing.

There's a fine line between what I'd want to check with unit tests and what I want to check during runtime with assertions. Usually unit tests are for testing a single unit of code when the rest of the application is in a well defined state (I use mock objects for this extensively) and I use debug.assert to check during runtime if the state of the application is as I expected.

Upvotes: 0

tanascius
tanascius

Reputation: 53944

I really like to support exceptionhandling during debugtime by using Debug.Assert() or even Debug.Fail():

if( !whatever_I_expect )
{
  var message = "<exception message>";
  Debug.Fail( message );
  throw new InvalidOperation( message );
}

This way I get the very handy dialog of Debug.Assert() and can choose between ignore, retry and abort. Retry will step into the code where I can start debugging. Especially recursive methods or complicated try-catch constructions can be better debugged this way. You always get the right call stack. And in my releasecode I still have a valid errorhandling without messageboxes.

Upvotes: 3

Untrots
Untrots

Reputation: 838

Of course in unit tests.

Outside unit tests I can identify 3 types of errors (very simplified):

  1. Critical internal error: Something that comes from inside of your code unit, that the user has no way to influence.
  2. Misuse of some functionality: For example giving a null instead of some value
  3. External problems: Such as non-existing file, no network connection, etc.

I think that assertions should be applied only to the first one. Number two and three should be handled using appropriate exceptions.

Upvotes: 0

Gerrie Schenck
Gerrie Schenck

Reputation: 22368

There was a good discussion about the usage of Debug.Assert() a while back: Debug.Assert vs Exceptions

Upvotes: 2

plinth
plinth

Reputation: 49179

I prefer to use unit tests to flesh out problems. Since my main product is a library/assembly, it's also necessary to make sure that arguments are validated and appropriate exceptions thrown.

Interesting note: Debug.Assert() is trapped by the MS C# compiler in a release build and removed.

Upvotes: 0

Sasha
Sasha

Reputation:

Google should give you plenty of examples (hint: type csharp example assert)

http://en.csharp-online.net/Assert

Upvotes: 0

REA_ANDREW
REA_ANDREW

Reputation: 10764

The immediate answer I can think of is when you are testing code:

Assert.IsNotNull(yourVariable);

You can also use the Debug.Assert

System.Diagnostics.Debug.Assert(myBooleanProperty);

Upvotes: 0

Related Questions