Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>I would like to reduce "8 lines" of code to 1.</p> </blockquote> <p>I think you're asking the wrong question. It's not how many lines of code you have, it's how clear, maintainable, and debuggable they are. From what you've described, importing from a default location and importing with a known file are <strong>semantically different</strong> - so I think you're correct in separating them as two different overloads. In fact, you may want to go further and actually <em>name them differently</em> to further clarify the difference.</p> <blockquote> <p>I'm genuinely curious if C# is capable of something like this.</p> </blockquote> <p>Sure, we can use all sorts of fancy language tricks to make this more compact ... but I don't think they make the code more clear. For instance:</p> <pre><code>// build a Action delegate based on the argument... Action importAction = string.IsNullOrEmpty(arguments.File) ? () =&gt; importer.StartImport() : () =&gt; importer.StartImport(arguments.File) importAction(); // invoke the delegate... </code></pre> <p>The code above uses a lambda + <a href="https://stackoverflow.com/questions/595482/what-are-closures-in-c">closure</a> to create a <code>Action</code> delegate of the right type, which is then invoked. But this is hardly more clear ... it's also slightly less efficient, as it requires creating a delegate and then invoking the method through that delegate. In most cases the performance overhead is completely negligible. The real problem here is the use of the closure - it's very easy to misuse code with closures - and it's entirely possible to <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx" rel="nofollow noreferrer">introduce bugs</a> by using <a href="http://msmvps.com/blogs/peterritchie/archive/2010/11/03/deep-dive-on-closure-pitfals.aspx" rel="nofollow noreferrer">closures incorrectly</a>.</p>
 

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