Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's one way to get what I think you're asking for:</p> <pre><code>static class Argument { public static void NotNull(Expression&lt;Func&lt;Func&lt;object&gt;&gt;&gt; arg) { if (arg.Compile()()() == null) { var body1 = (Expression&lt;Func&lt;object&gt;&gt;)arg.Body; var body2 = (MemberExpression)body1.Body; throw new ArgumentNullException(body2.Member.Name); } } } </code></pre> <p>Used like this:</p> <pre><code>void F(string foo) { Argument.NotNull(() =&gt; () =&gt; foo); </code></pre> <p>The great thing about this is that renaming <code>foo</code> in the IDE will get all the references. (If you have <code>foo</code> in a string, it will get missed.)</p> <p>If you use this in a tight loop, it may cause performance problems, because it calls <code>.Compile()()</code> each time. You can optimize for performance by adding this overload:</p> <pre><code> public static void NotNull(object value, Expression&lt;Func&lt;Func&lt;object&gt;&gt;&gt; arg) { if (value == null) { var body1 = (Expression&lt;Func&lt;object&gt;&gt;)arg.Body; var body2 = (MemberExpression)body1.Body; throw new ArgumentNullException(body2.Member.Name); } } </code></pre> <p>Which is used like this:</p> <pre><code>Argument.NotNull(foo, () =&gt; () =&gt; foo); </code></pre> <p>It still gets renames correct, and it saves that call on each iteration.</p> <p>What I would recommend is using the first version when you write your code, then run it under a profiler, and switch to the second version in the cases that matter.</p>
    singulars
    1. This table or related slice is empty.
    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. 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