Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can get this information using AOP. You can define an intercept that is invoked before method execution and throw the exception there. This also takes care of the problem that null checking is a cross-cutting concern.</p> <p><a href="http://www.postsharp.org/" rel="nofollow noreferrer">PostSharp</a> is a good simple implementation of AOP.</p> <p>Here's what your code would look like (haven't tested, but it should get you very close)</p> <pre><code>[AttributeUsage(AttributeTargets.Parameter)] public class CanBeNullAttribute : Attribute { private readonly bool canBeNull; public CanBeNullAttribute() : this(true) { } public CanBeNullAttribute(bool canBeNull) { this.canBeNull = canBeNull; } public bool AllowNull { get { return canBeNull; } } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class EnforceNullConstraintAttribute : OnMethodInvocationAspect { public override void OnInvocation(MethodInvocationEventArgs eventArgs) { object[] arguments = eventArgs.GetArgumentArray(); ParameterInfo[] parameters = eventArgs.Delegate.Method.GetParameters(); for (int i = 0; i &lt; arguments.Length; i++) { if (arguments[i] != null) continue; foreach (CanBeNullAttribute attribute in parameters[i].GetCustomAttributes(typeof(CanBeNullAttribute), true)) { if (!attribute.AllowNull) throw new ArgumentNullException(parameters[i].Name); } } base.OnInvocation(eventArgs); } } </code></pre> <p>Now, you can modify your method:</p> <pre><code>[EnforceNullConstraint] public void Woof([CanBeNull(false)] object resource) { // no need to check for null, PostSharp will weave it at compile time // execute logic assured that "resource" is not null } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload