Not logged in - Login

Parameter validation using Contract

Parameters can be validated by using the Contract class.

Example:

private void Foo(object p_obj, string p_obj2)
{
#if DEBUG
    // do the contract validation here.
    System.Diagnostics.Contracts.Contract.Requires(p_obj != null, "Parameter 'p_obj' cannot be null");
    System.Diagnostics.Contracts.Contract.Requires(!string.IsNullOrWhiteSpace(p_obj2), "Parameter 'p_obj2' cannot be blank");
#else
    // do NOT use the above contract validation in RELEASE mode
    if (p_obj == null) throw new ArgumentNullException("p_obj ");
    if (string.IsNullOrWhiteSpace(p_obj2)) throw new ArgumentNullException("p_obj2");
#endif

    // the rest of the method body would go here.
    int x = 0;
    x++;
}

Important: Do NOT use this technique for any kind of password or security validation. It can be overridden and bypassed.