0

Recently, I came across the Debug.Assert in C#. However this has been into programming for years but this came across to me as new & quite puzzled me.

Lets say I have C# method where input field is mandatory like

public class User
{
   public class GetUser(string email) // email is required field
   {
       if(!string.IsNullOrEmptySpace(email)
       {
            
          //ToDo
        
       }
   }


   public class GetUserByEmail(string email) // email is required field
   {
         Debug.Assert(email != null); 
         //Assert method takes a boolean value and throws an exception if the value is false

        // ToDo
        
   }
}

What is the difference between these 2 approaches or use-case of the second approach?

Should I continue using Debug.Assert lib in .Net Core?

Thanks!

2
  • 3
    One throws an exception (if the executable was compiled for DEBUG), the other one doesn't. You shouldn't use Debug.Assert for normal business logic, because it gets removed when compiled for release. It's for sanity checks only.
    – Andy
    Apr 22, 2021 at 5:22
  • That's a slightly odd way of conceiving of asserts. In most parts of your code, in which X should NEVER be true, you should assert that X is not true. You should NOT test for it in runtime code and then have two separate code paths to deal with each case. This is what junior engineers often do, and it makes the codebase needlessly complex. You should continually test and improve your code such that the assert never fails, rather than accepting that you don't fully understand your code but put in some emergency code handling the case that goes wrong for reasons you don't understand.
    – Kaitain
    Aug 21, 2022 at 16:04

1 Answer 1

2

Debug.Assert as you see throws an exception when it receives a false value. We use this to validate developer assumptions. For example: lets say you just coded a function that requires the passed in parameter to be positive. So you want to make sure that no developer on your team passes a negative value. So you would use Debug.Assert there. However, this line gets completely removed if you build RELEASE so do NOT use it for business logic. Its just a helper to ensure that you have not forgotten an assumption you made while writing some logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.