<p>This came to my mind after I learned the following from <a href="http://www.stackoverflow.com/questions/8941/generic-type-checking">this question</a>:</p>

<pre><code>where T : struct
</code></pre>

<p>We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.</p>

<p>Some of us even mastered the stuff like <a href="http://msdn.microsoft.com/en-us/library/512aeb7t.aspx" rel="nofollow noreferrer">Generics</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397696.aspx" rel="nofollow noreferrer">anonymous types</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" rel="nofollow noreferrer">lambdas</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397676.aspx" rel="nofollow noreferrer">LINQ</a>, ...</p>

<p>But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?</p>

<h1>Here are the revealed features so far:</h1>

<p><br /></p>

<h2>Keywords</h2>

<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx" rel="nofollow noreferrer"><code>yield</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><code>var</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><code>using()</code> statement by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li><code>readonly</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li><code>as</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9041#9041">Mike Stone</a></li>
<li><code>as</code> / <code>is</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9070#9070">Ed Swangren</a></li>
<li><code>as</code> / <code>is</code> (improved) by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9092#9092">Rocketpants</a></li>
<li><code>default</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9639#9639">deathofrats</a></li>
<li><code>global::</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12152#12152">pzycoman</a></li>
<li><code>using()</code> blocks by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12316#12316">AlexCuse</a></li>
<li><code>volatile</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/59691#59691">Jakub Šturc</a></li>
<li><code>extern alias</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/37926#37926">Jakub Šturc</a></li>
</ul>

<h2>Attributes</h2>

<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx" rel="nofollow noreferrer"><code>DefaultValueAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx" rel="nofollow noreferrer"><code>ObsoleteAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037">DannySmurf</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.aspx" rel="nofollow noreferrer"><code>DebuggerDisplayAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9048#9048">Stu</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx" rel="nofollow noreferrer"><code>DebuggerBrowsable</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx" rel="nofollow noreferrer"><code>DebuggerStepThrough</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/33474#33474">bdukes</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx" rel="nofollow noreferrer"><code>ThreadStaticAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932">marxidad</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx" rel="nofollow noreferrer"><code>FlagsAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/21752#21752">Martin Clarke</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/4xssyw96.aspx" rel="nofollow noreferrer"><code>ConditionalAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/35342#35342">AndrewBurns</a></li>
</ul>

<h2>Syntax</h2>

<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms173224.aspx" rel="nofollow noreferrer"><code>??</code></a> (coalesce nulls) operator by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li>Number flaggings by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9038#9038">Nick Berardi</a></li>
<li><code>where T:new</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9067#9067">Lars Mæhlum</a></li>
<li>Implicit generics by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>One-parameter lambdas by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Auto properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Namespace aliases by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Verbatim string literals with @ by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9114#9114">Patrick</a></li>
<li><code>enum</code> values by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/11738#11738">lfoust</a></li>
<li>@variablenames by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14088#14088">marxidad</a></li>
<li><code>event</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14277#14277">marxidad</a></li>
<li>Format string brackets by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15321#15321">Portman</a></li>
<li>Property accessor accessibility modifiers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15715#15715">xanadont</a></li>
<li>Conditional (ternary) operator (<code>?:</code>) by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16450#16450">JasonS</a></li>
<li><code>checked</code> and <code>unchecked</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/355991#355991">Binoj Antony</a></li>
<li><code>implicit and explicit</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/121470#121470">Flory</a></li>
</ul>

<h2>Language Features</h2>

<ul>
<li>Nullable types by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9055#9055">Brad Barker</a></li>
<li>Anonymous types by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li><code>__makeref __reftype __refvalue</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9125#9125">Judah Himango</a></li>
<li>Object initializers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9547#9547">lomaxx</a></li>
<li>Format strings by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/10207#10207">David in Dakota</a></li>
<li>Extension Methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932">marxidad</a></li>
<li><code>partial</code> methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16395#16395">Jon Erickson</a></li>
<li>Preprocessor directives by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16482#16482">John Asbeck</a></li>
<li><code>DEBUG</code> pre-processor directive by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/29081#29081">Robert Durgin</a></li>
<li>Operator overloading by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/24914#24914">SefBkn</a></li>
<li>Type inferrence by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/28811#28811">chakrit</a></li>
<li>Boolean operators <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm" rel="nofollow noreferrer">taken to next level</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/32148#32148">Rob Gough</a></li>
<li>Pass value-type variable as interface without boxing by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1820538#1820538">Roman Boiko</a></li>
<li>Programmatically determine declared variable type by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1789985#1789985">Roman Boiko</a></li>
<li>Static Constructors by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/100321#100321">Chris</a></li>
<li>Easier-on-the-eyes / condensed ORM-mapping using LINQ by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/2026781#2026781">roosteronacid</a></li>
<li><code>__arglist</code> by <a href="https://stackoverflow.com/a/1836944/171819">Zac Bowling</a></li>
</ul>

<h2>Visual Studio Features</h2>

<ul>
<li>Select block of text in editor by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1699477#1699477" title="block text selecting with alt key">Himadri</a></li>
<li>Snippets by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037">DannySmurf</a>  </li>
</ul>

<h2>Framework</h2>

<ul>
<li><code>TransactionScope</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>DependantTransaction</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>Nullable&lt;T&gt;</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9118#9118">IainMH</a></li>
<li><code>Mutex</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9181#9181">Diago</a></li>
<li><code>System.IO.Path</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9401#9401">ageektrapped</a></li>
<li><code>WeakReference</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14723#14723">Juan Manuel</a></li>
</ul>

<h2>Methods and Properties</h2>

<ul>
<li><code>String.IsNullOrEmpty()</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>List.ForEach()</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>BeginInvoke()</code>, <code>EndInvoke()</code> methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9581#9581">Will Dean</a></li>
<li><code>Nullable&lt;T&gt;.HasValue</code> and <code>Nullable&lt;T&gt;.Value</code> properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15393#15393">Rismo</a></li>
<li><code>GetValueOrDefault</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/18158#18158">John Sheehan</a></li>
</ul>

<h2>Tips &amp; Tricks</h2>

<ul>
<li>Nice method for event handlers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9282#9282">Andreas H.R. Nilsson</a></li>
<li>Uppercase comparisons by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12137#12137">John</a></li>
<li>Access anonymous types without reflection by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13441#13441">dp</a></li>
<li>A quick way to lazily instantiate collection properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/58945#58945">Will</a></li>
<li>JavaScript-like anonymous inline-functions by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1399130#1399130">roosteronacid</a></li>
</ul>

<h2>Other</h2>

<ul>
<li>netmodules by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a>  </li>
<li><a href="http://www.albahari.com/nutshell/linqbridge.html" rel="nofollow noreferrer">LINQBridge</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/10886#10886">Duncan Smart</a>  </li>
<li><a href="http://msdn.microsoft.com/en-us/concurrency/default.aspx" rel="nofollow noreferrer">Parallel Extensions</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/31293#31293">Joel Coehoorn</a></li>
</ul>

[{'answer_id': 9035, 'author': 'Michael Stum', 'author_id': 91, 'author_profile': 'https://Stackoverflow.com/users/91', 'pm_score': 8, 'selected': False, 'text': '<p>"<a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx" rel="nofollow noreferrer">yield</a>" would come to my mind. Some of the attributes like <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx" rel="nofollow noreferrer">[DefaultValue()]</a> are also among my favorites.</p>\n\n<p>The "<a href="http://msdn.microsoft.com/en-us/library/bb383973.aspx" rel="nofollow noreferrer">var</a>" keyword is a bit more known, but that you can use it in .NET 2.0 applications as well (as long as you <a href="http://blogs.msdn.com/msbuild/archive/2006/11/03/msbuild-orcas-and-multi-targeting.aspx" rel="nofollow noreferrer">use the .NET 3.5 compiler</a> and set it to output 2.0 code) does not seem to be known very well.</p>\n\n<p>Edit: kokos, thanks for pointing out the ?? operator, that\'s indeed really useful. Since it\'s a bit hard to google for it (as ?? is just ignored), here is the MSDN documentation page for that operator: <em><a href="http://msdn.microsoft.com/en-us/library/ms173224.aspx" rel="nofollow noreferrer">?? Operator (C# Reference)</a></em></p>\n'}, {'answer_id': 9036, 'author': 'kokos', 'author_id': 1065, 'author_profile': 'https://Stackoverflow.com/users/1065', 'pm_score': 7, 'selected': False, 'text': '<ol>\n<li><a href="http://msdn.microsoft.com/en-us/library/ms173224.aspx" rel="nofollow noreferrer">??</a> - coalescing operator  </li>\n<li>using (<a href="http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx" rel="nofollow noreferrer">statement</a> / <a href="http://msdn.microsoft.com/en-us/library/sf0df423(VS.71).aspx" rel="nofollow noreferrer">directive</a>) - great keyword that can be used for more than just calling Dispose  </li>\n<li><a href="http://msdn.microsoft.com/en-us/library/acdd6hb7(VS.100).aspx" rel="nofollow noreferrer">readonly</a> - should be used more  </li>\n<li>netmodules - too bad there\'s no support in Visual Studio</li>\n</ol>\n'}, {'answer_id': 9037, 'author': 'TheSmurf', 'author_id': 1975282, 'author_profile': 'https://Stackoverflow.com/users/1975282', 'pm_score': 5, 'selected': False, 'text': '<p>Two of my personal favourites, which I see rarely used:</p>\n\n<ol>\n<li>Snippets (particularly for properties, which was made even better for Visual Studio 2008)</li>\n<li>The <a href="http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx" rel="nofollow noreferrer">ObsoleteAttribute</a></li>\n</ol>\n'}, {'answer_id': 9038, 'author': 'Nick Berardi', 'author_id': 17, 'author_profile': 'https://Stackoverflow.com/users/17', 'pm_score': 6, 'selected': False, 'text': '<p>Honestly the experts by the very definition should know this stuff.  But to answer your question: <em><a href="http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx" rel="nofollow noreferrer">Built-In Types Table (C# Reference)</a></em></p>\n\n<p>The compiler flagging for numbers are widely known for these:</p>\n\n<pre><code>Decimal = M\nFloat = F\nDouble = D\n\n// for example\ndouble d = 30D;\n</code></pre>\n\n<p>However these are more obscure:</p>\n\n<pre><code>Long = L\nUnsigned Long = UL\nUnsigned Int = U\n</code></pre>\n'}, {'answer_id': 9041, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 8, 'selected': False, 'text': '<p>I didn\'t know the "as" keyword for quite a while.</p>\n\n<pre><code>MyClass myObject = (MyClass) obj;\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>MyClass myObject = obj as MyClass;\n</code></pre>\n\n<p>The second will return null if obj isn\'t a MyClass, rather than throw a class cast exception.</p>\n'}, {'answer_id': 9042, 'author': 'JamesSugrue', 'author_id': 1075, 'author_profile': 'https://Stackoverflow.com/users/1075', 'pm_score': 6, 'selected': False, 'text': '<ul>\n<li>TransactionScope and <a href="http://msdn.microsoft.com/en-us/library/system.transactions.dependenttransaction.aspx" rel="nofollow noreferrer">DependentTransaction</a> in System.Transactions is a lightweight way to use transaction processing in .NET - it\'s not just for <a href="http://msdn.microsoft.com/en-us/library/ms229973.aspx" rel="nofollow noreferrer">Database transactions either</a></li>\n<li>String.IsNullOrEmpty is one that I am surprised to learn a lot of developers don\'t know about</li>\n<li>List.ForEach - iterate through your generic list using a delegate method</li>\n</ul>\n\n<p>There are more, but that is the three obvious ones of the top of my head...</p>\n'}, {'answer_id': 9048, 'author': 'Stu', 'author_id': 414, 'author_profile': 'https://Stackoverflow.com/users/414', 'pm_score': 8, 'selected': False, 'text': '<p>Attributes in general, but most of all <a href="http://msdn.microsoft.com/en-us/library/x810d419.aspx" rel="nofollow noreferrer">DebuggerDisplay</a>. Saves you years.</p>\n'}, {'answer_id': 9055, 'author': 'Brad Barker', 'author_id': 12081, 'author_profile': 'https://Stackoverflow.com/users/12081', 'pm_score': 8, 'selected': False, 'text': '<p>I tend to find that most C# developers don\'t know about \'nullable\' types. Basically, primitives that can have a null value.</p>\n\n<pre><code>double? num1 = null; \ndouble num2 = num1 ?? -100;\n</code></pre>\n\n<p>Set a nullable double, <em>num1</em>, to null, then set a regular double, <em>num2</em>, to <em>num1</em> or <em>-100</em> if <em>num1</em> was null.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx</a></p>\n\n<p>one more thing about Nullable type:</p>\n\n<pre><code>DateTime? tmp = new DateTime();\ntmp = null;\nreturn tmp.ToString();\n</code></pre>\n\n<p>it is return String.Empty. Check <a href="https://stackoverflow.com/questions/4547112/is-nullable-datetime-work-correct">this</a> link for more details</p>\n'}, {'answer_id': 9067, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 4, 'selected': False, 'text': '<p>I have often come across the need to have a generic parameter-object persisted into the viewstate in a base class.</p>\n\n<pre><code>public abstract class BaseListControl&lt;ListType,KeyType,ParameterType&gt;\n                 : UserControl \n                 where ListType : BaseListType\n                 &amp;&amp; ParameterType : BaseParameterType, new\n{\n\n    private const string viewStateFilterKey = "FilterKey";\n\n    protected ParameterType Filters\n    {\n        get\n        {\n            if (ViewState[viewStateFilterKey] == null)\n                ViewState[viewStateFilterKey]= new ParameterType();\n\n            return ViewState[viewStateFilterKey] as ParameterType;\n        }\n        set\n        {\n            ViewState[viewStateFilterKey] = value;\n        }\n    }\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>private void SomeEventHappened(object sender, EventArgs e)\n{\n    Filters.SomeValue = SomeControl.SelectedValue;\n}\n\nprivate void TimeToFetchSomeData()\n{\n    GridView.DataSource = Repository.GetList(Filters);\n}\n</code></pre>\n\n<p>This little trick with the "where ParameterType : BaseParameterType, new" is what makes it really work.</p>\n\n<p>With this property in my baseclass, I can automate handling of paging, setting filter values to filter a gridview, make sorting really easy, etc.</p>\n\n<p>I am really just saying that generics can be an enormously powerful beast in the wrong hands.</p>\n'}, {'answer_id': 9092, 'author': 'Dogmang', 'author_id': 1135, 'author_profile': 'https://Stackoverflow.com/users/1135', 'pm_score': 7, 'selected': False, 'text': "<p>@Ed, I'm a bit reticent about posting this as it's little more than nitpicking. However, I would point out that in your code sample:</p>\n\n<pre><code>MyClass c;\n  if (obj is MyClass)\n    c = obj as MyClass\n</code></pre>\n\n<p>If you're going to use 'is', why follow it up with a safe cast using 'as'? If you've ascertained that obj is indeed MyClass, a bog-standard cast:</p>\n\n<pre><code>c = (MyClass)obj\n</code></pre>\n\n<p>...is never going to fail.</p>\n\n<p>Similarly, you could just say:</p>\n\n<pre><code>MyClass c = obj as MyClass;\nif(c != null)\n{\n   ...\n}\n</code></pre>\n\n<p>I don't know enough about .NET's innards to be sure, but my instincts tell me that this would cut a maximum of two type casts operations down to a maximum of one. It's hardly likely to break the processing bank either way; personally, I think the latter form looks cleaner too.</p>\n"}, {'answer_id': 9099, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 8, 'selected': False, 'text': '<p>Everything else, plus </p>\n\n<p>1) implicit generics (why only on methods and not on classes?)</p>\n\n<pre><code>void GenericMethod&lt;T&gt;( T input ) { ... }\n\n//Infer type, so\nGenericMethod&lt;int&gt;(23); //You don\'t need the &lt;&gt;.\nGenericMethod(23);      //Is enough.\n</code></pre>\n\n<p>2) simple lambdas with one parameter:</p>\n\n<pre><code>x =&gt; x.ToString() //simplify so many calls\n</code></pre>\n\n<p>3) anonymous types and initialisers:</p>\n\n<pre><code>//Duck-typed: works with any .Add method.\nvar colours = new Dictionary&lt;string, string&gt; {\n    { "red", "#ff0000" },\n    { "green", "#00ff00" },\n    { "blue", "#0000ff" }\n};\n\nint[] arrayOfInt = { 1, 2, 3, 4, 5 };\n</code></pre>\n\n<hr>\n\n<p>Another one:</p>\n\n<p>4) Auto properties can have different scopes:</p>\n\n<pre><code>public int MyId { get; private set; }\n</code></pre>\n\n<hr>\n\n<p>Thanks @pzycoman for reminding me:</p>\n\n<p>5) Namespace aliases (not that you\'re likely to need this particular distinction):</p>\n\n<pre><code>using web = System.Web.UI.WebControls;\nusing win = System.Windows.Forms;\n\nweb::Control aWebControl = new web::Control();\nwin::Control aFormControl = new win::Control();\n</code></pre>\n'}, {'answer_id': 9114, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 7, 'selected': False, 'text': '<p>Here\'s a useful one for regular expressions and file paths:</p>\n\n<pre><code>"c:\\\\program files\\\\oldway"\n@"c:\\program file\\newway"\n</code></pre>\n\n<p>The @ tells the compiler to ignore any escape characters in a string.</p>\n'}, {'answer_id': 9118, 'author': 'Iain Holder', 'author_id': 1122, 'author_profile': 'https://Stackoverflow.com/users/1122', 'pm_score': 3, 'selected': False, 'text': '<p>@Brad Barker</p>\n\n<p>I think if you have to use nullable types, it\'s better to use Nullable&lt;.T> rather than the question mark notation.  It makes it eye-achingly obvious that magic is occurring.\nNot sure why anyone would ever want to use Nullable&lt;.bool> though. :-)</p>\n\n<p>Krzysztof Cwalina (one of the authors of Framwork Design Guidlines) has a good post here:\n<a href="http://blogs.msdn.com/kcwalina/archive/2008/07/16/Nullable.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/kcwalina/archive/2008/07/16/Nullable.aspx</a></p>\n\n<p>And Mike Hadlow has a nice post on <a href="http://mikehadlow.blogspot.com/2006/10/nullability-voodoo.html" rel="nofollow noreferrer">Nullability Voodoo</a></p>\n'}, {'answer_id': 9125, 'author': 'Judah Gabriel Himango', 'author_id': 536, 'author_profile': 'https://Stackoverflow.com/users/536', 'pm_score': 8, 'selected': False, 'text': '<p>Here are some interesting hidden C# features, in the form of undocumented C# keywords:</p>\n\n<pre><code>__makeref\n\n__reftype\n\n__refvalue\n\n__arglist\n</code></pre>\n\n<p>These are undocumented C# keywords (even Visual Studio recognizes them!) that were added to for a more efficient boxing/unboxing prior to generics. They work in coordination with the System.TypedReference struct.</p>\n\n<p>There\'s also __arglist, which is used for variable length parameter lists.</p>\n\n<p>One thing folks don\'t know much about is <a href="http://msdn.microsoft.com/en-us/library/ms404247.aspx" rel="noreferrer">System.WeakReference</a> -- a very useful class that keeps track of an object but still allows the garbage collector to collect it.</p>\n\n<p>The most useful "hidden" feature would be the yield return keyword. It\'s not really hidden, but a lot of folks don\'t know about it. LINQ is built atop this; it allows for delay-executed queries by generating a state machine under the hood. Raymond Chen recently posted about the <a href="http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx" rel="noreferrer">internal, gritty details</a>.</p>\n'}, {'answer_id': 9129, 'author': 'Michael Stum', 'author_id': 91, 'author_profile': 'https://Stackoverflow.com/users/91', 'pm_score': 7, 'selected': False, 'text': '<blockquote>\n  <p>Not sure why anyone would ever want to use Nullable&lt;bool> though. :-)</p>\n</blockquote>\n\n<p>True, False, <a href="http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx" rel="nofollow noreferrer">FileNotFound</a>?</p>\n'}, {'answer_id': 9181, 'author': 'BinaryMisfit', 'author_id': 146270, 'author_profile': 'https://Stackoverflow.com/users/146270', 'pm_score': 3, 'selected': False, 'text': '<p>In no particular order:</p>\n\n<pre><code>Lists&lt;&gt;\nMutex\n</code></pre>\n\n<p>The new property definitions shortcut in Framework 3.5.</p>\n'}, {'answer_id': 9282, 'author': 'andynil', 'author_id': 446, 'author_profile': 'https://Stackoverflow.com/users/446', 'pm_score': 8, 'selected': False, 'text': '<p><strong>Avoid checking for null event handlers</strong></p>\n\n<p>Adding an empty delegate to events at declaration, suppressing the need to always check the event for null before calling it is awesome. Example:</p>\n\n<pre><code>public delegate void MyClickHandler(object sender, string myValue);\npublic event MyClickHandler Click = delegate {}; // add empty delegate!\n</code></pre>\n\n<p>Let you do this</p>\n\n<pre><code>public void DoSomething()\n{\n    Click(this, "foo");\n}\n</code></pre>\n\n<p>Instead of this</p>\n\n<pre><code>public void DoSomething()\n{\n    // Unnecessary!\n    MyClickHandler click = Click;\n    if (click != null) // Unnecessary! \n    {\n        click(this, "foo");\n    }\n}\n</code></pre>\n\n<p>Please also see this <a href="https://stackoverflow.com/questions/840715/the-proper-way-of-raising-events-in-the-net-framework">related discussion</a> and this <a href="http://blogs.msdn.com/ericlippert/archive/2009/04/29/events-and-races.aspx" rel="nofollow noreferrer">blog post</a> by Eric Lippert on this topic (and possible downsides).</p>\n'}, {'answer_id': 9401, 'author': 'ageektrapped', 'author_id': 631, 'author_profile': 'https://Stackoverflow.com/users/631', 'pm_score': 10, 'selected': False, 'text': '<p>This isn\'t C# per se, but I haven\'t seen anyone who really uses <code>System.IO.Path.Combine()</code> to the extent that they should. In fact, the whole Path class is really useful, but <strong>no one uses it!</strong></p>\n\n<p>I\'m willing to bet that every production app has the following code, even though it shouldn\'t:</p>\n\n<pre><code>string path = dir + "\\\\" + fileName;\n</code></pre>\n'}, {'answer_id': 9406, 'author': 'lomaxx', 'author_id': 493, 'author_profile': 'https://Stackoverflow.com/users/493', 'pm_score': 8, 'selected': False, 'text': '<blockquote>\n  <p>The @ tells the compiler to ignore any\n  escape characters in a string.</p>\n</blockquote>\n\n<p>Just wanted to clarify this one... it doesn\'t tell it to ignore the escape characters, it actually tells the compiler to interpret the string as a literal.</p>\n\n<p>If you have </p>\n\n<pre><code>string s = @"cat\n             dog\n             fish"\n</code></pre>\n\n<p>it will actually print out as (note that it even includes the whitespace used for indentation):</p>\n\n<pre><code>cat\n             dog\n             fish\n</code></pre>\n'}, {'answer_id': 9547, 'author': 'lomaxx', 'author_id': 493, 'author_profile': 'https://Stackoverflow.com/users/493', 'pm_score': 8, 'selected': False, 'text': '<p>Two things I like are Automatic properties so you can collapse your code down even further:</p>\n\n<pre><code>private string _name;\npublic string Name\n{\n    get\n    {\n        return _name;\n    }\n    set\n    {\n        _name = value;\n    }\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>public string Name { get; set;}\n</code></pre>\n\n<p>Also object initializers:</p>\n\n<pre><code>Employee emp = new Employee();\nemp.Name = "John Smith";\nemp.StartDate = DateTime.Now();\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>Employee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()}\n</code></pre>\n'}, {'answer_id': 9581, 'author': 'Will Dean', 'author_id': 987, 'author_profile': 'https://Stackoverflow.com/users/987', 'pm_score': 4, 'selected': False, 'text': '<p>On the basis that this thread should be entitled "<em>things you didn\'t know about C# until recently despite thinking you already knew everything</em>", my personal feature is asynchronous delegates.</p>\n\n<p>Until I read Jeff Richter\'s C#/CLR book (excellent book, everyone doing .NET should read it) I didn\'t know that you could call <em>any</em> delegate using <code>BeginInvoke</code> / <code>EndInvoke</code>.  I tend to do a lot of <code>ThreadPool.QueueUserWorkItem</code> calls (which I guess is much like what the delegate <code>BeginInvoke</code> is doing internally), but the addition of a standardised join/rendezvous pattern may be really useful sometimes.</p>\n'}, {'answer_id': 9639, 'author': 'Eric Minkes', 'author_id': 1172, 'author_profile': 'https://Stackoverflow.com/users/1172', 'pm_score': 8, 'selected': False, 'text': "<p>The 'default' keyword in generic types:</p>\n\n<pre><code>T t = default(T);\n</code></pre>\n\n<p>results in a 'null' if T is a reference type, and 0 if it is an int, false if it is a boolean,\netcetera.</p>\n"}, {'answer_id': 10207, 'author': 't3rse', 'author_id': 64, 'author_profile': 'https://Stackoverflow.com/users/64', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Lambda Expressions</strong></p>\n\n<pre><code>Func&lt;int, int, int&gt; add = (a, b) =&gt; (a + b);\n</code></pre>\n\n<p><strong>Obscure String Formats</strong></p>\n\n<pre><code>Console.WriteLine("{0:D10}", 2); // 0000000002\n\nDictionary&lt;string, string&gt; dict = new Dictionary&lt;string, string&gt; { \n    {"David", "C#"}, \n    {"Johann", "Perl"}, \n    {"Morgan", "Python"}\n};\n\nConsole.WriteLine( "{0,10} {1, 10}", "Programmer", "Language" );\n\nConsole.WriteLine( "-".PadRight( 21, \'-\' ) );\n\nforeach (string key in dict.Keys)\n{\n    Console.WriteLine( "{0, 10} {1, 10}", key, dict[key] );             \n}\n</code></pre>\n'}, {'answer_id': 10886, 'author': 'Duncan Smart', 'author_id': 1278, 'author_profile': 'https://Stackoverflow.com/users/1278', 'pm_score': 4, 'selected': False, 'text': '<p>I love the fact that I can use LINQ to objects on plain old .NET 2.0 (i.e. without requiring .NET 3.5 to be installed everywhere). All you need is an implementation of all the query operator Extension methods - see <a href="http://www.albahari.com/nutshell/linqbridge.html" rel="nofollow noreferrer">LINQBridge</a></p>\n'}, {'answer_id': 10892, 'author': 'Serhat Ozgel', 'author_id': 31505, 'author_profile': 'https://Stackoverflow.com/users/31505', 'pm_score': 3, 'selected': False, 'text': "<p>In addition to duncansmart's reply, also extension methods can be used on Framework 2.0. Just add an <code>ExtensionAttribute</code> class under System.Runtime.CompilerServices namespace and you can use extension methods (only with C# 3.0 of course).</p>\n\n<pre><code>namespace System.Runtime.CompilerServices\n{\n    public class ExtensionAttribute : Attribute\n    { \n    }\n}\n</code></pre>\n"}, {'answer_id': 11738, 'author': 'Luke Foust', 'author_id': 646, 'author_profile': 'https://Stackoverflow.com/users/646', 'pm_score': 5, 'selected': False, 'text': '<p>Being able to have enum types have values other than int (the default)</p>\n\n<pre><code>public enum MyEnum : long\n{\n    Val1 = 1,\n    Val2 = 2\n}\n</code></pre>\n\n<p>Also, the fact that you can assign any numeric value to that enum:</p>\n\n<pre><code>MyEnum e = (MyEnum)123;\n</code></pre>\n'}, {'answer_id': 12137, 'author': 'jfs', 'author_id': 718, 'author_profile': 'https://Stackoverflow.com/users/718', 'pm_score': 9, 'selected': False, 'text': '<blockquote>\n  <p>From <a href="https://rads.stackoverflow.com/amzn/click/com/0735621632" rel="noreferrer" rel="nofollow noreferrer">CLR via C#</a>:</p>\n  \n  <p>When normalizing strings, it is highly\n  recommended that you use\n  ToUpperInvariant instead of\n  ToLowerInvariant because <strong>Microsoft has\n  optimized the code for performing\n  uppercase comparisons</strong>.</p>\n</blockquote>\n\n<p>I remember one time my coworker always changed strings to uppercase before comparing. I\'ve always wondered why he does that because I feel it\'s more "natural" to convert to lowercase first. After reading the book now I know why.</p>\n'}, {'answer_id': 12152, 'author': 'Surgical Coder', 'author_id': 1276, 'author_profile': 'https://Stackoverflow.com/users/1276', 'pm_score': 5, 'selected': False, 'text': '<p>My favourite is the</p>\n\n<pre><code>global::\n</code></pre>\n\n<p>keyword to escape namespace hell with some of our 3rd party code providers...</p>\n\n<p>Example:</p>\n\n<pre><code>global::System.Collections.Generic.List&lt;global::System.String&gt; myList =\n    new global::System.Collections.Generic.List&lt;global::System.String&gt;();\n</code></pre>\n'}, {'answer_id': 12316, 'author': 'AlexCuse', 'author_id': 794, 'author_profile': 'https://Stackoverflow.com/users/794', 'pm_score': 4, 'selected': False, 'text': '<p>I didn\'t start to really appreciate the "using" blocks until recently.  They make things so much more tidy :)</p>\n'}, {'answer_id': 13422, 'author': 'Brad Wilson', 'author_id': 1554, 'author_profile': 'https://Stackoverflow.com/users/1554', 'pm_score': 7, 'selected': False, 'text': '<p>This one is not "hidden" so much as it is misnamed.</p>\n\n<p>A lot of attention is paid to the algorithms "map", "reduce", and "filter". What most people don\'t realize is that .NET 3.5 added all three of these algorithms, but it gave them very SQL-ish names, based on the fact that they\'re part of LINQ.</p>\n\n<blockquote>\n  <p>"map" => Select <br>Transforms data\n  from one form into another</p>\n  \n  <p>"reduce" => Aggregate <br>Aggregates\n  values into a single result</p>\n  \n  <p>"filter" => Where <br>Filters data\n  based on a criteria</p>\n</blockquote>\n\n<p>The ability to use LINQ to do inline work on collections that used to take iteration and conditionals can be incredibly valuable. It\'s worth learning how all the LINQ extension methods can help make your code much more compact and maintainable.</p>\n'}, {'answer_id': 13441, 'author': 'denis phillips', 'author_id': 748, 'author_profile': 'https://Stackoverflow.com/users/748', 'pm_score': 7, 'selected': False, 'text': '<p>Returning anonymous types from a method and accessing members without reflection.</p>\n\n<pre><code>// Useful? probably not.\nprivate void foo()\n{\n    var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) });\n    Console.WriteLine("Name: {0} Badges: {1}", user.Name, user.Badges);\n}\n\nobject GetUserTuple()\n{\n    return new { Name = "dp", Badges = 5 };\n}    \n\n// Using the magic of Type Inference...\nstatic T AnonCast&lt;T&gt;(object obj, T t)\n{\n   return (T) obj;\n}\n</code></pre>\n'}, {'answer_id': 13932, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 5, 'selected': False, 'text': '<p>There\'s also the ThreadStaticAttribute to make a static field unique per thread, so you can have strongly typed thread-local storage.</p>\n\n<p>Even if extension methods aren\'t that secret (LINQ is based on them), it may not be so obvious as to how useful and more readable they can be for utility helper methods:</p>\n\n<pre><code>//for adding multiple elements to a collection that doesn\'t have AddRange\n//e.g., collection.Add(item1, item2, itemN);\nstatic void Add&lt;T&gt;(this ICollection&lt;T&gt; coll, params T[] items)\n { foreach (var item in items) coll.Add(item);\n }\n\n//like string.Format() but with custom string representation of arguments\n//e.g., "{0} {1} {2}".Format&lt;Custom&gt;(c=&gt;c.Name,"string",new object(),new Custom())\n//      result: "string {System.Object} Custom1Name"\nstatic string Format&lt;T&gt;(this string format, Func&lt;T,object&gt; select, params object[] args)\n { for(int i=0; i &lt; args.Length; ++i)\n    { var x = args[i] as T;\n      if (x != null) args[i] = select(x);\n    }\n   return string.Format(format, args);\n }\n</code></pre>\n'}, {'answer_id': 14036, 'author': 'Pat Hermens', 'author_id': 1677, 'author_profile': 'https://Stackoverflow.com/users/1677', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n  <p>I think if you have to use nullable\n  types, it\'s better to use Nullable&lt;.T>\n  rather than the question mark\n  notation. It makes it eye-achingly\n  obvious that magic is occurring. Not\n  sure why anyone would ever want to use\n  Nullable&lt;.bool> though.</p>\n</blockquote>\n\n<p>In a VB.NET Web service where the parameter might not be passed through <em>(because the partners request wasn\'t consistent or reliable)</em>, but had to pass validation against the proposed type <em>(Boolean for "if is search request")</em>. Chalk it up to "another demand by management"...</p>\n\n<p><em>...and yes, I know some people think it\'s not the right way to do these things, but <strong>IsSearchRequest As Nullable(Of Boolean)</strong> saved me losing my mind that night!</em></p>\n'}, {'answer_id': 14088, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 7, 'selected': False, 'text': '<p>Using @ for variable names that are keywords.</p>\n\n<pre><code>var @object = new object();\nvar @string = "";\nvar @if = IpsoFacto(); \n</code></pre>\n'}, {'answer_id': 14277, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 6, 'selected': False, 'text': '<p>Events are really delegates under the hood and any delegate object can have multiple functions attached to it  and detatched from it using the += and -= operators, respectively.</p>\n\n<p>Events can also be controlled with the add/remove, similar to get/set except they\'re invoked when += and -= are used:</p>\n\n<pre><code>public event EventHandler SelectiveEvent(object sender, EventArgs args) \n  { add \n     { if (value.Target == null) throw new Exception("No static handlers!");\n       _SelectiveEvent += value;\n     }\n    remove\n     { _SelectiveEvent -= value;\n     }\n  } EventHandler _SelectiveEvent;\n</code></pre>\n'}, {'answer_id': 14723, 'author': 'juan', 'author_id': 1782, 'author_profile': 'https://Stackoverflow.com/users/1782', 'pm_score': 5, 'selected': False, 'text': '<p>It\'s not actually a C# hidden feature, but I recently discovered the <a href="http://msdn.microsoft.com/en-us/library/system.weakreference.aspx" rel="nofollow noreferrer">WeakReference class</a> and was blown away by it (although this may be biased by the fact that it helped me found a solution to a <a href="http://www.juanformoso.com.ar/post/2008/07/30/Weak-References.aspx" rel="nofollow noreferrer">particular problem of mine</a>...)</p>\n'}, {'answer_id': 14926, 'author': 'martinlund', 'author_id': 1808, 'author_profile': 'https://Stackoverflow.com/users/1808', 'pm_score': 2, 'selected': False, 'text': "<p>I must admit that i'm not sure wether this performs better or worse than the normal ASP.NET repeater onItemDatabound cast code, but anyway here's my 5 cent.</p>\n\n<pre><code>MyObject obj = e.Item.DataItem as MyObject;\nif(obj != null)\n{\n  //Do work\n}\n</code></pre>\n"}, {'answer_id': 15321, 'author': 'Portman', 'author_id': 1690, 'author_profile': 'https://Stackoverflow.com/users/1690', 'pm_score': 7, 'selected': False, 'text': '<p>If you\'re trying to use curly brackets inside a String.Format expression...</p>\n\n<pre><code>int foo = 3;\nstring bar = "blind mice";\nString.Format("{{I am in brackets!}} {0} {1}", foo, bar);\n//Outputs "{I am in brackets!} 3 blind mice"\n</code></pre>\n'}, {'answer_id': 15352, 'author': 'mgsloan', 'author_id': 1164871, 'author_profile': 'https://Stackoverflow.com/users/1164871', 'pm_score': 5, 'selected': False, 'text': "<p>Near all the cool ones have been mentioned.  Not sure if this one's well known or not</p>\n\n<p>C# property/field constructor initialization:</p>\n\n<pre><code>var foo = new Rectangle() \n{ \n    Fill = new SolidColorBrush(c), \n    Width = 20, \n    Height = 20 \n};\n</code></pre>\n\n<p>This creates the rectangle, and sets the listed properties.</p>\n\n<p>I've noticed something funny - you can have a comma at the end of the properties list, without it being a syntax error.  So this is also valid:</p>\n\n<pre><code>var foo = new Rectangle() \n{ \n    Fill = new SolidColorBrush(c), \n    Width = 20, \n    Height = 20,\n};\n</code></pre>\n"}, {'answer_id': 15393, 'author': 'Rismo', 'author_id': 1560, 'author_profile': 'https://Stackoverflow.com/users/1560', 'pm_score': 5, 'selected': False, 'text': '<p>Not hidden, but I think that a lot of developers are not using the HasValue and Value properties on the nullable types.</p>\n\n<pre><code>        int? x = null;\n        int y;\n        if (x.HasValue)\n            y = x.Value;\n</code></pre>\n'}, {'answer_id': 15715, 'author': 'xanadont', 'author_id': 1886, 'author_profile': 'https://Stackoverflow.com/users/1886', 'pm_score': 5, 'selected': False, 'text': '<p>@lomaxx I also learned the other day (the same time I learned your tip) is that you can now have disparate access levels on the same property:</p>\n\n<pre><code>public string Name { get; private set;}\n</code></pre>\n\n<p>That way only the class itself can set the Name property.</p>\n\n<pre><code>public MyClass(string name) { Name = name; }\n</code></pre>\n'}, {'answer_id': 15765, 'author': 'jfs', 'author_id': 718, 'author_profile': 'https://Stackoverflow.com/users/718', 'pm_score': 9, 'selected': False, 'text': '<p>From <a href="http://www.west-wind.com/weblog/posts/236298.aspx" rel="nofollow noreferrer">Rick Strahl</a>:</p>\n\n<p>You can chain the ?? operator so that you can do a bunch of null comparisons.</p>\n\n<pre><code>string result = value1 ?? value2 ?? value3 ?? String.Empty;\n</code></pre>\n'}, {'answer_id': 16395, 'author': 'Jon Erickson', 'author_id': 1950, 'author_profile': 'https://Stackoverflow.com/users/1950', 'pm_score': 5, 'selected': False, 'text': '<h1>Partial Methods</h1>\n\n<p><a href="http://blogs.msdn.com/charlie/archive/2007/11/11/partial-methods.aspx" rel="nofollow noreferrer">Charlie Calvert explains partial methods on his blog</a></p>\n\n<p><a href="http://weblogs.asp.net/scottcate/archive/2008/06/18/teched-orlando-compiler-tricks.aspx" rel="nofollow noreferrer">Scott Cate has a nice partial method demo here</a></p>\n\n<ol>\n<li>Points of extensibility in Code Generated class (LINQ to SQL, EF)</li>\n<li>Does not get compiled into the dll if it is not implemented (check it out with .NET Reflector)</li>\n</ol>\n'}, {'answer_id': 16450, 'author': 'JasonS', 'author_id': 1865, 'author_profile': 'https://Stackoverflow.com/users/1865', 'pm_score': 7, 'selected': False, 'text': '<p>Maybe not an advanced technique, but one I see all the time that drives me crazy:</p>\n\n<pre><code>if (x == 1)\n{\n   x = 2;\n}\nelse\n{\n   x = 3;\n}\n</code></pre>\n\n<p>can be condensed to:</p>\n\n<pre><code>x = (x==1) ? 2 : 3;\n</code></pre>\n'}, {'answer_id': 16482, 'author': 'John Asbeck', 'author_id': 1767, 'author_profile': 'https://Stackoverflow.com/users/1767', 'pm_score': 3, 'selected': False, 'text': '<p>Preprocessor Directives can be nifty if you want different behavior between Debug and Release modes.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx</a></p>\n'}, {'answer_id': 18158, 'author': 'John Sheehan', 'author_id': 1786, 'author_profile': 'https://Stackoverflow.com/users/1786', 'pm_score': 4, 'selected': False, 'text': '<p>I see a lot of people replicate the functionality of <code>Nullable&lt;T&gt;.GetValueOrDefault(T)</code>.</p>\n'}, {'answer_id': 18619, 'author': 'Nelson Miranda', 'author_id': 1130097, 'author_profile': 'https://Stackoverflow.com/users/1130097', 'pm_score': 3, 'selected': False, 'text': '<p>You type "prop" and then press [TAB] twice, it generates useful code for your properties and can speed your typing.</p>\n\n<p>I know this works in VS 2005 (I use it) but I don´t know in previous versions.</p>\n'}, {'answer_id': 21752, 'author': 'Martin Clarke', 'author_id': 2422, 'author_profile': 'https://Stackoverflow.com/users/2422', 'pm_score': 4, 'selected': False, 'text': '<p>How about the <a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx" rel="noreferrer">FlagsAttribute</a> on an enumeration? It allows you to perform bitwise operations... took me forever to find out how to do bitwise operations in .NET nicely.</p>\n'}, {'answer_id': 24914, 'author': 'SemiColon', 'author_id': 1994, 'author_profile': 'https://Stackoverflow.com/users/1994', 'pm_score': 3, 'selected': False, 'text': '<p>I\'m pretty sure everyone is familiar with operator overloading, but maybe some aren\'t.</p>\n\n<pre><code>class myClass\n{\n    private string myClassValue = "";\n\n    public myClass(string myString)\n    {\n        myClassValue = myString;\n    }\n\n    public override string ToString()\n    {\n        return myClassValue;\n    }\n\n    public static myClass operator &lt;&lt;(myClass mc, int shiftLen)\n    {\n        string newString = "";\n        for (int i = shiftLen; i &lt; mc.myClassValue.Length; i++)\n            newString += mc.myClassValue[i].ToString();\n        mc.myClassValue = newString.ToString();\n        return mc;\n    }\n\n    public static myClass operator &gt;&gt;(myClass mc, int shiftLen)\n    {\n        char[] newString = new char[shiftLen + mc.myClassValue.Length];\n\n        for (int i = shiftLen; i &lt; mc.myClassValue.Length; i++)\n            newString[i] += mc.myClassValue[i - shiftLen];\n\n        mc.myClassValue = new string(newString);\n        return mc;\n    }\n\n    public static myClass operator +(myClass mc, string args)\n    {\n        if (args.Trim().Length &gt; 1)\n            mc.myClassValue += args;\n        return mc;\n    }\n\n    public static myClass operator -(myClass mc, string args)\n    {\n        if (args.Trim().Length &gt; 1)\n        {\n            Regex rgx = new Regex(args);\n            mc.myClassValue = rgx.Replace(mc.myClassValue, "");\n        }\n        return mc;\n    }\n}\n</code></pre>\n\n<p>I think it\'s pretty cool to be able to shift a string left and right using &lt;&lt; and >> or to remove a set of strings that follow a regular expression pattern using -=</p>\n\n<pre><code>myClass tmpClass = new myClass("  HelloWorld123");\ntmpClass -= @"World";\ntmpClass &lt;&lt;= 2;\nConsole.WriteLine(tmpClass);\n</code></pre>\n'}, {'answer_id': 25393, 'author': 'Haacked', 'author_id': 598, 'author_profile': 'https://Stackoverflow.com/users/598', 'pm_score': 2, 'selected': False, 'text': '<p>One interesting thing I\'ve learned is that different parts of the framework and C# language were written at different times, hence inconsistencies. For example, the framework itself violates many FxCop rules because the rules weren\'t all in place when the framework was written.</p>\n\n<p>Also, the using statement was intended for delinieating "scopes" and not specifically for disposing resources. It was written after the lock statement. Eric Gunnerson <a href="http://haacked.com/archive/2004/05/27/DifficultiesOfLanguageDesign.aspx" rel="nofollow noreferrer">once mentioned</a> something along the lines of that if the using statement came first, they might have not needed to write the lock statement (though who knows, maybe they would have anyways), because the using statement might have been sufficient.</p>\n'}, {'answer_id': 26096, 'author': 'John Boker', 'author_id': 2847, 'author_profile': 'https://Stackoverflow.com/users/2847', 'pm_score': 3, 'selected': False, 'text': '<p>@lainMH,</p>\n\n<p>Nullable booleans are useful when retrieving values from a database that are nullable and when putting values back in. Sometimes you want to know the field has not been set.</p>\n'}, {'answer_id': 26192, 'author': 'David Basarab', 'author_id': 2469, 'author_profile': 'https://Stackoverflow.com/users/2469', 'pm_score': 3, 'selected': False, 'text': '<p>In reading the book on development of the .NET framework.  A good piece of advice is not to use bool to turn stuff on or off, but rather use ENums.</p>\n\n<p>With ENums you give yourself some expandability without having to rewrite any code to add a new feature to a function.</p>\n'}, {'answer_id': 27941, 'author': 'Frep D-Oronge', 'author_id': 3024, 'author_profile': 'https://Stackoverflow.com/users/3024', 'pm_score': 5, 'selected': False, 'text': '<p>The C# ?? null coalescing operator - </p>\n\n<p>Not really hidden, but rarely used. Probably because a lot of developers run a mile when they see the conditional ? operator, so they run two when they see this one. Used:</p>\n\n<pre><code>string mystring = foo ?? "foo was null"\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>string mystring;\nif (foo==null)\n    mystring = "foo was null";\nelse\n    mystring = foo;\n</code></pre>\n'}, {'answer_id': 28811, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 9, 'selected': False, 'text': '<p><strong>lambdas and type inference</strong> are underrated. <strong>Lambdas can have multiple statements</strong> and they <strong>double as a compatible delegate object</strong> automatically (just make sure the signature match) as in:</p>\n\n<pre><code>Console.CancelKeyPress +=\n    (sender, e) =&gt; {\n        Console.WriteLine("CTRL+C detected!\\n");\n        e.Cancel = true;\n    };\n</code></pre>\n\n<p>Note that I don\'t have a <code>new CancellationEventHandler</code> nor do I have to specify types of <code>sender</code> and <code>e</code>, they\'re inferable from the event. Which is why this is less cumbersome to writing the whole <code>delegate (blah blah)</code> which also requires you to specify types of parameters.</p>\n\n<p><strong>Lambdas don\'t need to return anything</strong> and type inference is extremely powerful in context like this.</p>\n\n<p>And BTW, you can always return <strong>Lambdas that make Lambdas</strong> in the functional programming sense. For example, here\'s a lambda that makes a lambda that handles a Button.Click event:</p>\n\n<pre><code>Func&lt;int, int, EventHandler&gt; makeHandler =\n    (dx, dy) =&gt; (sender, e) =&gt; {\n        var btn = (Button) sender;\n        btn.Top += dy;\n        btn.Left += dx;\n    };\n\nbtnUp.Click += makeHandler(0, -1);\nbtnDown.Click += makeHandler(0, 1);\nbtnLeft.Click += makeHandler(-1, 0);\nbtnRight.Click += makeHandler(1, 0);\n</code></pre>\n\n<p>Note the chaining: <code>(dx, dy) =&gt; (sender, e) =&gt;</code></p>\n\n<p>Now that\'s why I\'m happy to have taken the functional programming class :-)</p>\n\n<p>Other than the pointers in C, I think it\'s the other fundamental thing you should learn :-)</p>\n'}, {'answer_id': 28830, 'author': 'Drakiula', 'author_id': 2437, 'author_profile': 'https://Stackoverflow.com/users/2437', 'pm_score': 3, 'selected': False, 'text': '<p>Reflection Emit and Expression trees come to mind...</p>\n\n<p>Don\'t miss Jeffrey Richter\'s CLR via C# and Jon Skeet\'s <img src="https://www.manning.com/skeet/skeet_cover150.jpg" alt="alt text"></p>\n\n<p>See here for some resources:</p>\n\n<p><a href="http://www.codeproject.com/KB/trace/releasemodebreakpoint.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/trace/releasemodebreakpoint.aspx</a></p>\n\n<p><a href="http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/dotnet/Creating_Dynamic_Types.aspx</a></p>\n\n<p><a href="http://www.codeproject.com/KB/cs/lambdaexpressions.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/lambdaexpressions.aspx</a></p>\n'}, {'answer_id': 29081, 'author': 'Robert Durgin', 'author_id': 3132, 'author_profile': 'https://Stackoverflow.com/users/3132', 'pm_score': 5, 'selected': False, 'text': '<p>The <em>#if DEBUG</em> pre-processor directive. It is Useful for\ntesting and debugging (though I usually prefer to go the\nunit testing route).</p>\n\n<pre><code>string customerName = null;\n#if DEBUG\n  customerName = "Bob"\n#endif\n</code></pre>\n\n<p>It will only execute code block if Visual Studio is set to\ncompile in \'Debug\' mode. Otherwise the code block will be\nignored by the compiler (and grayed out in Visual Studio).</p>\n'}, {'answer_id': 31293, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 4, 'selected': False, 'text': '<p>I\'m late to this party, so my first choices are already taken.  But I didn\'t see anyone mention this gem yet:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/concurrency/default.aspx" rel="nofollow noreferrer">Parallel Extensions to the .NET Framework</a></p>\n\n<p>It has things like replace with Parallel.For or foreach with Parallel.ForEach</p>\n\n<hr>\n\n<p>Parallel Sample :<br>\nIn your opinion, how many CLR object can be created in one second?\n<img src="https://i.stack.imgur.com/nqJ2u.png" alt="enter image description here">\n<br>See fallowing example :</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace ObjectInitSpeedTest\n{\n   class Program\n   {\n       //Note: don\'t forget to build it in Release mode.\n       static void Main()\n       {\n           normalSpeedTest();           \n           parallelSpeedTest();\n\n           Console.ForegroundColor = ConsoleColor.White;\n           Console.WriteLine("Press a key ...");\n           Console.ReadKey();\n       }\n\n       private static void parallelSpeedTest()\n       {\n           Console.ForegroundColor = ConsoleColor.Yellow;\n           Console.WriteLine("parallelSpeedTest");\n\n           long totalObjectsCreated = 0;\n           long totalElapsedTime = 0;\n\n           var tasks = new List&lt;Task&gt;();\n           var processorCount = Environment.ProcessorCount;\n\n           Console.WriteLine("Running on {0} cores", processorCount);\n\n           for (var t = 0; t &lt; processorCount; t++)\n           {\n               tasks.Add(Task.Factory.StartNew(\n               () =&gt;\n               {\n                   const int reps = 1000000000;\n                   var sp = Stopwatch.StartNew();\n                   for (var j = 0; j &lt; reps; ++j)\n                   {\n                       new object();\n                   }\n                   sp.Stop();\n\n                   Interlocked.Add(ref totalObjectsCreated, reps);\n                   Interlocked.Add(ref totalElapsedTime, sp.ElapsedMilliseconds);\n               }\n               ));\n           }\n\n           // let\'s complete all the tasks\n           Task.WaitAll(tasks.ToArray());\n\n           Console.WriteLine("Created {0:N} objects in 1 sec\\n", (totalObjectsCreated / (totalElapsedTime / processorCount)) * 1000);\n       }\n\n       private static void normalSpeedTest()\n       {\n           Console.ForegroundColor = ConsoleColor.Green;\n           Console.WriteLine("normalSpeedTest");\n\n           const int reps = 1000000000;\n           var sp = Stopwatch.StartNew();\n           sp.Start();\n           for (var j = 0; j &lt; reps; ++j)\n           {\n               new object();\n           }\n           sp.Stop();\n\n           Console.WriteLine("Created {0:N} objects in 1 sec\\n", (reps / sp.ElapsedMilliseconds) * 1000);\n       }\n   }\n}\n</code></pre>\n'}, {'answer_id': 32148, 'author': 'Jakub Šturc', 'author_id': 2361, 'author_profile': 'https://Stackoverflow.com/users/2361', 'pm_score': 5, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx" rel="nofollow noreferrer">true</a> and <a href="http://msdn.microsoft.com/en-us/library/6292hy1k.aspx" rel="nofollow noreferrer">false</a> operators are really weird.</p>\n\n<p>More comprehensive example can be found <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm" rel="nofollow noreferrer">here</a>.</p>\n\n<p><em>Edit: There is related SO question <a href="https://stackoverflow.com/questions/33265/whats-the-false-operator-in-c-good-for">What’s the false operator in C# good for?</a></em></p>\n'}, {'answer_id': 32472, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Returning IQueryable projections</p>\n\n<pre><code>protected void LdsPostings_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{   \n    var dc = new MyDataContext();\n    var query = dc.Posting.AsQueryable();\n\n    if (isCondition1)\n    {\n        query = query.Where(q =&gt; q.PostedBy == Username);\n        e.Result = QueryProjection(query);\n        return;\n    }\n\n    ...\n\n    if (isConditionN)\n    {\n        query = query.Where(q =&gt; q.Status.StatusName == "submitted");\n        query = query.Where(q =&gt; q.ReviewedBy == Username);\n        e.Result = QueryProjection(query);\n        return;\n    }\n}\n</code></pre>\n\n<p>and rather than coding the projection multiple times, create a single method:</p>\n\n<pre><code>private IQueryable QueryProjection(IQueryable&lt;Posting&gt; query)\n{\n    return query.Select(p =&gt; new\n    {\n        p.PostingID,\n        p.Category.CategoryName,\n        p.Type.TypeName,\n        p.Status.StatusName,\n        p.Description,\n        p.Updated,\n        p.PostedBy,\n        p.ReviewedBy,\n    });\n}\n</code></pre>\n'}, {'answer_id': 32706, 'author': 'Nathan Lee', 'author_id': 3453, 'author_profile': 'https://Stackoverflow.com/users/3453', 'pm_score': 4, 'selected': False, 'text': '<p>I love using the @ character for SQL queries. It keeps the sql nice and formatted and without having to surround each line with a string delimiter.</p>\n\n<pre><code>string sql = @"SELECT firstname, lastname, email\n               FROM users\n               WHERE username = @username AND password = @password";\n</code></pre>\n'}, {'answer_id': 33271, 'author': 'chakrit', 'author_id': 3055, 'author_profile': 'https://Stackoverflow.com/users/3055', 'pm_score': 3, 'selected': False, 'text': '<p>Thought about <strong>@dp AnonCast</strong> and decided to try it out a bit. Here\'s what I come up with that might be useful to some:</p>\n\n<pre><code>// using the concepts of dp\'s AnonCast\nstatic Func&lt;T&gt; TypeCurry&lt;T&gt;(Func&lt;object&gt; f, T type)\n{\n    return () =&gt; (T)f();\n}\n</code></pre>\n\n<p>And here\'s how it might be used:</p>\n\n<pre><code>static void Main(string[] args)\n{\n\n    var getRandomObjectX = TypeCurry(GetRandomObject,\n        new { Name = default(string), Badges = default(int) });\n\n    do {\n\n        var obj = getRandomObjectX();\n\n        Console.WriteLine("Name : {0} Badges : {1}",\n            obj.Name,\n            obj.Badges);\n\n    } while (Console.ReadKey().Key != ConsoleKey.Escape);\n\n}\n\nstatic Random r = new Random();\nstatic object GetRandomObject()\n{\n    return new {\n        Name = Guid.NewGuid().ToString().Substring(0, 4),\n        Badges = r.Next(0, 100)\n    };\n}\n</code></pre>\n'}, {'answer_id': 33384, 'author': 'ljs', 'author_id': 3394, 'author_profile': 'https://Stackoverflow.com/users/3394', 'pm_score': 6, 'selected': False, 'text': '<p>I like looking up stuff in a list like:-</p>\n\n<pre><code>bool basketContainsFruit(string fruit) {\n  return new[] { "apple", "orange", "banana", "pear" }.Contains(fruit);\n}\n</code></pre>\n\n<p>Rather than:-</p>\n\n<pre><code>bool basketContainsFruit(string fruit) {\n  return fruit == "apple" || fruit == "orange" || fruit == "banana" ||\n    fruit == "pear";\n}\n</code></pre>\n\n<p>Doesn\'t come up that much in practice, but the idea of matching items against the subject of the search can be really quite useful + succinct.</p>\n'}, {'answer_id': 33474, 'author': 'bdukes', 'author_id': 2688, 'author_profile': 'https://Stackoverflow.com/users/2688', 'pm_score': 5, 'selected': False, 'text': '<p>A couple other attributes from the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.aspx" rel="nofollow noreferrer">System.Diagnostics</a> namespace are quite helpful.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx" rel="nofollow noreferrer">DebuggerBrowsable</a> will let you hide variables from the debugger window (we use it for all private backing variables of exposed properties).  Along with that, <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx" rel="nofollow noreferrer">DebuggerStepThrough</a> makes the debugger step over that code, very useful for dumb properties (probably should be converted to auto-properties if you can take a dependency to the C# 3.0 compiler).  As an example</p>\n\n<pre><code>[DebuggerBrowsable(DebuggerBrowsableState.Never)]\nprivate string nickName;\npublic string NickName    {\n    [DebuggerStepThrough]\n    get { return nickName; }\n    [DebuggerStepThrough]\n    set { this.nickName = value; }\n}\n</code></pre>\n'}, {'answer_id': 35342, 'author': 'Andrew Burns', 'author_id': 3683, 'author_profile': 'https://Stackoverflow.com/users/3683', 'pm_score': 4, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/aa664622(VS.71).aspx" rel="nofollow noreferrer">ConditionalAttribute</a></p>\n\n<p>Allows you to tell the compiler to omit the call to the method marked with the attribute under certain conditions (#define).</p>\n\n<p>The fact that the method call is omitted also means that its parameters are not evaluated. This is very handy and it\'s what allows you to call expensive validation functions in Debug.Assert() and not worry about them slowing down your release build. </p>\n'}, {'answer_id': 37285, 'author': 'nimish', 'author_id': 3926, 'author_profile': 'https://Stackoverflow.com/users/3926', 'pm_score': 7, 'selected': False, 'text': '<pre><code>Environment.NewLine\n</code></pre>\n\n<p>for system independent newlines.</p>\n'}, {'answer_id': 37467, 'author': 'jfs', 'author_id': 718, 'author_profile': 'https://Stackoverflow.com/users/718', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Nesting Using Statements</strong></p>\n\n<p>Usually we do it like this:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nusing (StringWriter sw = new StringWriter()) {\n    using (IndentedTextWriter itw = new IndentedTextWriter(sw)) {\n        ... \n    }\n}\n</code></pre>\n\n<p>But we can do it this way:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nusing (StringWriter sw = new StringWriter())\nusing (IndentedTextWriter itw = new IndentedTextWriter(sw)) {\n    ... \n}\n</code></pre>\n'}, {'answer_id': 37926, 'author': 'Jakub Šturc', 'author_id': 2361, 'author_profile': 'https://Stackoverflow.com/users/2361', 'pm_score': 4, 'selected': False, 'text': '<p>The <a href="http://msdn.microsoft.com/en-us/library/ms173212.aspx" rel="nofollow noreferrer">extern alias</a> keyword to reference two versions of assemblies that have the same fully-qualified type names.</p>\n'}, {'answer_id': 38703, 'author': 'Eduardo Diaz', 'author_id': 3245, 'author_profile': 'https://Stackoverflow.com/users/3245', 'pm_score': 2, 'selected': False, 'text': '<p>PreviousPage property:</p>\n\n<p>"The System.Web.UI.Page representing the page that transferred control to the current page."</p>\n\n<p>It is very useful.</p>\n'}, {'answer_id': 41872, 'author': 'Michael Prewecki', 'author_id': 4403, 'author_profile': 'https://Stackoverflow.com/users/4403', 'pm_score': 2, 'selected': False, 'text': '<p>TryParse method for each primitive type is great when validating user input.</p>\n\n<pre><code>double doubleValue\nif (!Double.TryParse(myDataRow("myColumn"), out doubleValue))\n{\n    // set validation error\n}\n</code></pre>\n'}, {'answer_id': 44782, 'author': 'andynil', 'author_id': 446, 'author_profile': 'https://Stackoverflow.com/users/446', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Foreach uses Duck Typing</strong></p>\n\n<p>Paraphrasing, or shamelessly stealing from <a href="http://blogs.msdn.com/kcwalina/archive/2007/07/18/DuckNotation.aspx" rel="nofollow noreferrer">Krzysztof Cwalinas blog</a> on this. More interesting trivia than anything.</p>\n\n<p>For your object to support foreach, you <em>don\'t</em> have to implement <em>IEnumerable</em>. I.e. this is not a constraint and it isn\'t checked by the compiler. What\'s checked is that</p>\n\n<ul>\n<li>Your object provide a public method <em>GetEnumerator</em> that\n\n<ul>\n<li>takes no parameters</li>\n<li>return a type that has two members\n\n<ol>\n<li>a parameterless <em>method MoveNext</em> that <em>returns a boolean</em></li>\n<li>a <em>property Current</em> with a getter that <em>returns an Object</em></li>\n</ol></li>\n</ul></li>\n</ul>\n\n<p>For example,  </p>\n\n<pre><code>class Foo\n{\n    public Bar GetEnumerator() { return new Bar(); }\n\n    public struct Bar\n    {\n        public bool MoveNext()\n        {\n            return false;\n        }\n\n        public object Current\n        {\n            get { return null; }\n        }\n    }\n}\n\n// the following complies just fine:\nFoo f = new Foo();\nforeach (object o in f)\n{\n    Console.WriteLine("Krzysztof Cwalina\'s da man!");\n}\n</code></pre>\n'}, {'answer_id': 45398, 'author': 'Pop Catalin', 'author_id': 4685, 'author_profile': 'https://Stackoverflow.com/users/4685', 'pm_score': 5, 'selected': False, 'text': '<p>There are some really hidden keywords and features in C# related to the TypedReference undocumented class. The following keywords are undocumented:</p>\n\n<ul>\n<li><code>__makeref</code></li>\n<li><code>__reftype</code></li>\n<li><code>__refvalue</code></li>\n<li><code>__arglist</code></li>\n</ul>\n\n<p>Examples of use:</p>\n\n<pre><code>// Create a typed reference\nint i = 1;\nTypedReference tr1 = __makeref(i);\n// Get the type of a typed reference\nType t = __reftype(tr1);\n// Get the value of a typed referece\nint j = __refvalue(tr1, int); \n// Create a method that accepts and arbitrary number of typed references\nvoid SomeMethod(__arglist) { ...\n// Call the method\nint x = 1;\nstring y = "Foo";\nObject o = new Object();\nSomeMethod(__arglist(x,y,o));\n// And finally iterate over method parameters\nvoid SomeMethod(__arglist) {\n    ArgIterator ai = new ArgIterator(__arglist);\nwhile(ai.GetRemainingCount() &gt;0)\n{\n      TypedReference tr = ai.GetNextArg();\n      Console.WriteLine(TypedReference.ToObject(tr));\n}}\n</code></pre>\n'}, {'answer_id': 45454, 'author': 'Mark Ingram', 'author_id': 986, 'author_profile': 'https://Stackoverflow.com/users/986', 'pm_score': 2, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/9033?#9092">Robbie Rocketpants</a></p>\n\n<blockquote>\n  <p>"but my instincts tell me that this\n  would cut a maximum of two type casts\n  operations down to a maximum of one."</p>\n</blockquote>\n\n<p>If you do the cast as you were suggesting in example 1 (using is &amp; as), it results in 2 calls to the "is" operator. Because when you do "c = obj as MyClass", first it calls "is" behind the scenes, then if it fails that it simply returns null.</p>\n\n<p>If you do the cast as you were suggesting in example 2,</p>\n\n<pre><code>c = (MyClass)obj\n</code></pre>\n\n<p>Then this actually performs the "is" operation again, then if it fails that check,it throws an exception (InvalidCastException).</p>\n\n<p>So, if you wanted to do a lightweight dynamic cast, it\'s best to do the 3rd example you provided:</p>\n\n<pre><code>MyClass c;\nif (obj is MyClass)\n{\n    c = obj as MyClass\n}\n\nif (c != null)\n{\n}\n</code></pre>\n\n<p><strong>vs</strong></p>\n\n<pre><code>MyClass c = obj as MyClass;\n\nif (c != null)\n{\n}\n</code></pre>\n\n<p>You can see which is quicker, more consise and clearer.</p>\n'}, {'answer_id': 45873, 'author': 'Konamiman', 'author_id': 4574, 'author_profile': 'https://Stackoverflow.com/users/4574', 'pm_score': 6, 'selected': False, 'text': '<p>@David in Dakota:</p>\n\n<pre><code>Console.WriteLine( "-".PadRight( 21, \'-\' ) );\n</code></pre>\n\n<p>I used to do this, until I discovered that the String class has a constructor that allows you to do the same thing in a cleaner way:</p>\n\n<pre><code>new String(\'-\',22);\n</code></pre>\n'}, {'answer_id': 46157, 'author': 'DAC', 'author_id': 1111, 'author_profile': 'https://Stackoverflow.com/users/1111', 'pm_score': 6, 'selected': False, 'text': '<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx" rel="nofollow noreferrer">InternalsVisibleTo</a></strong> attribute is one that is not that well known, but can come in increadibly handy in certain circumstances. It basically allows another assembly to be able to access "internal" elements of the defining assembly.</p>\n'}, {'answer_id': 46290, 'author': 'Judah Gabriel Himango', 'author_id': 536, 'author_profile': 'https://Stackoverflow.com/users/536', 'pm_score': 5, 'selected': False, 'text': '<p>I just found out about this one today -- and I\'ve been working with C# for 5 years!</p>\n\n<p>It\'s the <a href="http://msdn.microsoft.com/en-us/library/ms173212(VS.80).aspx" rel="nofollow noreferrer">namespace alias qualifier</a>:</p>\n\n<pre><code>extern alias YourAliasHere;\n</code></pre>\n\n<p>You can use it to load multiple versions of the same type. This can be useful in maintenance or upgrade scenarios where you have an updated version of your type that won\'t work in some old code, but you need to upgrade it to the new version. <a href="http://blogs.msdn.com/abhinaba/archive/2005/11/30/498278.aspx" rel="nofollow noreferrer">Slap on a namespace alias qualifier</a>, and the compiler will let you have both types in your code.</p>\n'}, {'answer_id': 49607, 'author': 'nialljsmith', 'author_id': 5197, 'author_profile': 'https://Stackoverflow.com/users/5197', 'pm_score': 5, 'selected': False, 'text': '<p>I like the keyword <em>continue</em>.</p>\n\n<p>If you hit a condition in a loop and don\'t want to do anything but advance the loop just stick in "continue;".</p>\n\n<p>E.g.:</p>\n\n<pre><code>foreach(object o in ACollection)\n{\n  if(NotInterested)\n     continue;\n}\n</code></pre>\n'}, {'answer_id': 50891, 'author': 'johnc', 'author_id': 5302, 'author_profile': 'https://Stackoverflow.com/users/5302', 'pm_score': 3, 'selected': False, 'text': '<p>Not a C# specific thing, but I am a ternary operations junkie.</p>\n\n<p>Instead of </p>\n\n<pre><code>if (boolean Condition)\n{\n    //Do Function\n}\nelse\n{\n    //Do something else\n}\n</code></pre>\n\n<p>you can use a succinct</p>\n\n<pre><code>booleanCondtion ? true operation : false operation;\n</code></pre>\n\n<p>e.g.</p>\n\n<p>Instead of</p>\n\n<pre><code>int value = param;\nif (doubleValue)\n{\n    value *= 2;\n}\nelse\n{\n    value *= 3;\n}\n</code></pre>\n\n<p>you can type</p>\n\n<pre><code>int value = param * (tripleValue ? 3 : 2);\n</code></pre>\n\n<p>It does help write succinct code, but nesting the damn things can be nasty, and they can be used for evil, but I love the little suckers nonetheless</p>\n'}, {'answer_id': 51171, 'author': 'Thomas H', 'author_id': 4328, 'author_profile': 'https://Stackoverflow.com/users/4328', 'pm_score': 2, 'selected': False, 'text': "<p>Saw a mention of List.ForEach above; 2.0 introduced a bevy of predicate-based collection operations - Find, FindAll, Exists, etc.  Coupled with anonymous delegates you can almost achieve the simplicity of 3.5's lambda expressions.</p>\n"}, {'answer_id': 51966, 'author': 'Bryan', 'author_id': 5423, 'author_profile': 'https://Stackoverflow.com/users/5423', 'pm_score': 6, 'selected': False, 'text': '<p>A couple of things I like:</p>\n\n<p>-If you create an interface similar to</p>\n\n<pre><code> public interface SomeObject&lt;T&gt; where T : SomeObject&lt;T&gt;, new()\n</code></pre>\n\n<p>you force anything that inherits from this interface to \ncontain a parameterless constructor. It is very useful for a \ncouple of things I\'ve run across.</p>\n\n<p>-Using anonymous types to create a useful object on the fly:</p>\n\n<pre><code>var myAwesomeObject = new {Name="Foo", Size=10};\n</code></pre>\n\n<p>-Finally, many Java developers are familiar with syntax like:</p>\n\n<pre><code>public synchronized void MySynchronizedMethod(){}\n</code></pre>\n\n<p>However, in C# this is not valid syntax.  The workaround is a method attribute:</p>\n\n<pre><code> [MethodImpl(MethodImplOptions.Synchronized)]\n public void MySynchronizedMethod(){}\n</code></pre>\n'}, {'answer_id': 52998, 'author': 'Jason Olson', 'author_id': 5418, 'author_profile': 'https://Stackoverflow.com/users/5418', 'pm_score': 8, 'selected': False, 'text': '<p>I think one of the most under-appreciated and lesser-known features of C# (.NET 3.5) are <a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx" rel="nofollow noreferrer">Expression Trees</a>, <strong>especially</strong> when combined with Generics and Lambdas. This is an approach to API creation that newer libraries like NInject and Moq are using.</p>\n\n<p>For example, let\'s say that I want to register a method with an API and that API needs to get the method name</p>\n\n<p>Given this class:</p>\n\n<pre><code>public class MyClass\n{\n     public void SomeMethod() { /* Do Something */ }\n}\n</code></pre>\n\n<p>Before, it was very common to see developers do this with strings and types (or something else largely string-based):</p>\n\n<pre><code>RegisterMethod(typeof(MyClass), "SomeMethod");\n</code></pre>\n\n<p>Well, that sucks because of the lack of strong-typing. What if I rename "SomeMethod"? Now, in 3.5 however, I can do this in a strongly-typed fashion:</p>\n\n<pre><code>RegisterMethod&lt;MyClass&gt;(cl =&gt; cl.SomeMethod());\n</code></pre>\n\n<p>In which the RegisterMethod class uses <code>Expression&lt;Action&lt;T&gt;&gt;</code> like this:</p>\n\n<pre><code>void RegisterMethod&lt;T&gt;(Expression&lt;Action&lt;T&gt;&gt; action) where T : class\n{\n    var expression = (action.Body as MethodCallExpression);\n\n    if (expression != null)\n    {\n        // TODO: Register method\n        Console.WriteLine(expression.Method.Name);\n    }\n}\n</code></pre>\n\n<p>This is one big reason that I\'m in love with Lambdas and Expression Trees right now.</p>\n'}, {'answer_id': 58945, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 9, 'selected': False, 'text': '<p>My favorite trick is using the <a href="http://en.wikipedia.org/wiki/%3F%3F_Operator" rel="nofollow noreferrer">null coalesce operator</a> and parentheses to automagically instantiate collections for me.</p>\n\n<pre><code>private IList&lt;Foo&gt; _foo;\n\npublic IList&lt;Foo&gt; ListOfFoo \n    { get { return _foo ?? (_foo = new List&lt;Foo&gt;()); } }\n</code></pre>\n'}, {'answer_id': 59691, 'author': 'Jakub Šturc', 'author_id': 2361, 'author_profile': 'https://Stackoverflow.com/users/2361', 'pm_score': 6, 'selected': False, 'text': '<p>The <a href="http://msdn.microsoft.com/en-us/library/x13ttww7.aspx" rel="nofollow noreferrer">volatile</a> keyword to tell the compiler that a field can be modified by multiple threads concurrently.</p>\n'}, {'answer_id': 63661, 'author': 'Grokys', 'author_id': 6448, 'author_profile': 'https://Stackoverflow.com/users/6448', 'pm_score': 6, 'selected': False, 'text': '<p>I couldn\'t see this looking above - one that I didn\'t realise you could do until recently is to call one constructor from another:</p>\n\n<pre><code>class Example\n{\n    public Example(int value1)\n        : this(value1, "Default Value")\n    {\n    }\n\n    public Example(int value1, string value2)\n    {\n        m_Value1 = value1;\n        m_value2 = value2;\n    }\n\n    int m_Value1;\n    string m_value2;\n}\n</code></pre>\n'}, {'answer_id': 72518, 'author': 'Benjol', 'author_id': 11410, 'author_profile': 'https://Stackoverflow.com/users/11410', 'pm_score': 4, 'selected': False, 'text': '<ol>\n<li><p>I can\'t comment yet, but note that by default Visual Studio 2008 automatically steps over properties, so the DebuggerStepThrough attribute is no longer needed in that case.</p>\n</li>\n<li><p>Also, I haven\'t noticed anyone showing how to declare a parameter-less lambda (useful for implementing Action&lt;&gt;)</p>\n<p><code>() =&gt; DoSomething(x);</code></p>\n</li>\n</ol>\n<p>You should also read up on closures - I\'m not clever enough to explain them properly. But basically it means that the compiler does clever stuff so that the x in that line of code will still work even if it goes \'out of scope\' after creating the lambda.</p>\n<ol start="3">\n<li><p>I also discovered recently that you can pretend to ignore a lambda parameter:</p>\n<p><code>(e, _) =&gt; DoSomething(e)</code></p>\n</li>\n</ol>\n<p>It\'s not really ignoring it, it\'s just that _ is a valid identifier. So you couldn\'t ignore both of the parameters like that, but I think it is a kind of neat way to indicate that we don\'t care about that parameter (typically the EventArgs which is <code>.Empty</code>).</p>\n'}, {'answer_id': 73097, 'author': 'Thomas Danecker', 'author_id': 9632, 'author_profile': 'https://Stackoverflow.com/users/9632', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/system.runtime.remoting.proxies.realproxy.aspx" rel="nofollow noreferrer">System.Runtime.Remoting.Proxies.RealProxy</a></p>\n\n<p>It enables Aspect Oriented Programming in C#, and you can also do a lot of other fancy stuff with it.</p>\n'}, {'answer_id': 74482, 'author': 'BlackTigerX', 'author_id': 8411, 'author_profile': 'https://Stackoverflow.com/users/8411', 'pm_score': 9, 'selected': False, 'text': '<p>Aliased generics:</p>\n\n<pre><code>using ASimpleName = Dictionary&lt;string, Dictionary&lt;string, List&lt;string&gt;&gt;&gt;;\n</code></pre>\n\n<p>It allows you to use <code>ASimpleName</code>, instead of <code>Dictionary&lt;string, Dictionary&lt;string, List&lt;string&gt;&gt;&gt;</code>.</p>\n\n<p>Use it when you would use the same generic big long complex thing in a lot of places.</p>\n'}, {'answer_id': 87276, 'author': 'Sixto Saez', 'author_id': 9711, 'author_profile': 'https://Stackoverflow.com/users/9711', 'pm_score': 3, 'selected': False, 'text': '<p><strong>new modifier</strong></p>\n\n<p>Usage of the "new" modifier in C# is not exactly hidden but it\'s not often seen. The new modifier comes in handy when you need to "hide" base class members and not always override them. This means when you cast the derived class as the base class then the "hidden" method becomes visible and is called instead of the same method in the derived class.</p>\n\n<p>It is easier to see in code:</p>\n\n<pre><code>public class BaseFoo\n{\n    virtual public void DoSomething()\n    {\n        Console.WriteLine("Foo");\n    }\n}\n\npublic class DerivedFoo : BaseFoo\n{\n    public new void DoSomething()\n    {\n        Console.WriteLine("Bar");\n    }\n}\n\npublic class DerivedBar : BaseFoo\n{\n    public override void DoSomething()\n    {\n        Console.WriteLine("FooBar");\n    }\n}\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        BaseFoo derivedBarAsBaseFoo = new DerivedBar();\n        BaseFoo derivedFooAsBaseFoo = new DerivedFoo();\n\n        DerivedFoo derivedFoo = new DerivedFoo();\n\n        derivedFooAsBaseFoo.DoSomething(); //Prints "Foo" when you might expect "Bar"\n        derivedBarAsBaseFoo.DoSomething(); //Prints "FooBar"\n\n        derivedFoo.DoSomething(); //Prints "Bar"\n    }\n}\n</code></pre>\n\n<p>[Ed: Do I get extra points for puns? Sorry, couldn\'t be helped.]</p>\n'}, {'answer_id': 89505, 'author': 'John Spurlock', 'author_id': 3054, 'author_profile': 'https://Stackoverflow.com/users/3054', 'pm_score': 6, 'selected': False, 'text': '<p>Don\'t forget about <strong><a href="http://msdn.microsoft.com/en-us/library/13940fs2(VS.71).aspx" rel="nofollow noreferrer">goto</a></strong>.</p>\n'}, {'answer_id': 90432, 'author': 'Alex Lyman', 'author_id': 5897, 'author_profile': 'https://Stackoverflow.com/users/5897', 'pm_score': 4, 'selected': False, 'text': '<p>Falling through <code>switch</code>-<code>case</code>s can be achieved by having no code in a <code>case</code> (see <code>case 0</code>), or using the special <code>goto case</code> (see <code>case 1</code>) or <code>goto default</code> (see <code>case 2</code>) forms:</p>\n\n<pre><code>switch (/*...*/) {\n    case 0: // shares the exact same code as case 1\n    case 1:\n        // do something\n        goto case 2;\n    case 2:\n        // do something else\n        goto default;\n    default:\n        // do something entirely different\n        break;\n}\n</code></pre>\n'}, {'answer_id': 99844, 'author': 'Statement', 'author_id': 2166173, 'author_profile': 'https://Stackoverflow.com/users/2166173', 'pm_score': 2, 'selected': False, 'text': '<p>The #region <em>{string}</em> and #endregion pair is very neat for grouping code (outlining).</p>\n\n<pre><code>#region Using statements\nusing System;\nusing System.IO;\nusing ....;\nusing ....;\n#endregion\n</code></pre>\n\n<p>The code block can be compressed to a single describing line of text. Works inside functions aswell. </p>\n'}, {'answer_id': 100321, 'author': 'core', 'author_id': 11574, 'author_profile': 'https://Stackoverflow.com/users/11574', 'pm_score': 5, 'selected': False, 'text': '<p>Static constructors.</p>\n\n<p>Instances:</p>\n\n<pre><code>public class Example\n{\n    static Example()\n    {\n        // Code to execute during type initialization\n    }\n\n    public Example()\n    {\n        // Code to execute during object initialization\n    }\n}\n</code></pre>\n\n<p>Static classes:</p>\n\n<pre><code>public static class Example\n{\n    static Example()\n    {\n        // Code to execute during type initialization\n    }\n}\n</code></pre>\n\n<p>MSDN <a href="http://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx" rel="nofollow noreferrer">says</a>:</p>\n\n<blockquote>\n  <p>A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.</p>\n</blockquote>\n\n<p>For example:</p>\n\n<pre><code>public class MyWebService\n{\n    public static DateTime StartTime;\n\n    static MyWebService()\n    {\n        MyWebService.StartTime = DateTime.Now;\n    }\n\n    public TimeSpan Uptime\n    {\n        get { return DateTime.Now - MyWebService.StartTime; }\n    }\n}\n</code></pre>\n\n<p>But, you could also just as easily have done:</p>\n\n<pre><code>public class MyWebService\n{\n    public static DateTime StartTime = DateTime.Now;\n\n    public TimeSpan Uptime\n    {\n        get { return DateTime.Now - MyWebService.StartTime; }\n    }\n}\n</code></pre>\n\n<p>So you\'ll be hard-pressed to find any instance when you actually need to use a static constructor.</p>\n\n<p>MSDN offers useful notes on static constructors:</p>\n\n<blockquote>\n  <ul>\n  <li><p>A static constructor does not take access modifiers or have parameters.</p></li>\n  <li><p>A static constructor is called automatically to initialize the class \n  before the first instance is created<br>\n  or any static members are referenced.</p></li>\n  <li><p>A static constructor cannot be called directly.</p></li>\n  <li><p>The user has no control on when the static constructor is executed in the \n  program.</p></li>\n  <li><p>A typical use of static constructors is when the class is\n  using a log file and the\n  constructor is used to write<br>\n  entries to this file.</p></li>\n  <li><p>Static constructors are also useful when creating wrapper classes for<br>\n  unmanaged code, when the constructor<br>\n  can call the LoadLibrary method.</p></li>\n  <li><p>If a static constructor throws an exception, the runtime will not<br>\n  invoke it a second time, and the type \n  will remain uninitialized for the<br>\n  lifetime of the application domain in \n  which your program is running.</p></li>\n  </ul>\n</blockquote>\n\n<p>The most important note is that if an error occurs in the static constructor, a <code>TypeIntializationException</code> is thrown and you cannot drill down to the offending line of code. Instead, you have to examine the <code>TypeInitializationException</code>\'s <code>InnerException</code> member, which is the specific cause.</p>\n'}, {'answer_id': 102358, 'author': 'Rob', 'author_id': 18505, 'author_profile': 'https://Stackoverflow.com/users/18505', 'pm_score': 2, 'selected': False, 'text': '<p>Some concurrency utilities in the BCL might qualify as hidden features.</p>\n\n<p>Things like System.Threading.Monitor are used internally by the lock keyword; clearly in C# the lock keyword is preferrable, but sometimes it pays to know how things are done at a lower level; I had to lock in C++/CLI, so I encased a block of code with calls to Monitor.Enter() and Monitor.Exit().</p>\n'}, {'answer_id': 103235, 'author': 'ilitirit', 'author_id': 9825, 'author_profile': 'https://Stackoverflow.com/users/9825', 'pm_score': 3, 'selected': False, 'text': '<p>Literals can be used as variables of that type.\neg.</p>\n\n<pre><code>Console.WriteLine(5.ToString());\nConsole.WriteLine(5M.GetType());   // Returns "System.Decimal"\nConsole.WriteLine("This is a string!!!".Replace("!!", "!"));\n</code></pre>\n\n<p>Just a bit of trivia...</p>\n\n<p>There\'s quite a few things people haven\'t mentioned, but they have mostly to do with unsafe constructs.  Here\'s one that can be used by "regular" code though:</p>\n\n<p>The checked/unchecked keywords:</p>\n\n<pre><code>public static int UncheckedAddition(int a, int b)\n{\n    unchecked { return a + b; }\n}\n\npublic static int CheckedAddition(int a, int b)\n{\n    checked { return a + b; } // or "return checked(a + b)";\n}\n\npublic static void Main() \n{\n    Console.WriteLine("Unchecked: " + UncheckedAddition(Int32.MaxValue, + 1));  // "Wraps around"\n    Console.WriteLine("Checked: " + CheckedAddition(Int32.MaxValue, + 1));  // Throws an Overflow exception\n    Console.ReadLine();\n}\n</code></pre>\n'}, {'answer_id': 103449, 'author': 'William Yeung', 'author_id': 16371, 'author_profile': 'https://Stackoverflow.com/users/16371', 'pm_score': 2, 'selected': False, 'text': '<p>Before lambda comes into play, it\'s anonymous delegate. That could be used for blanket code similar to Ruby\'s blockgiven. I haven\'t tested how lambda works though because I want to stick with .NET 2.0 so far.</p>\n\n<p>For example when you want to make sure you remember to close your HTML tags:</p>\n\n<pre><code>MyHtmlWriter writer=new MyHtmlWriter();\nwriter.writeTag("html", \n  delegate ()\n  { \n    writer.writeTag("head", \n       delegate() \n       { \n           writer.writeTag("title"...);\n       }\n    )\n  })\n</code></pre>\n\n<p>I am sure if lambda is an option, that could yield much cleaner code :)</p>\n'}, {'answer_id': 104738, 'author': 'ripper234', 'author_id': 11236, 'author_profile': 'https://Stackoverflow.com/users/11236', 'pm_score': 1, 'selected': False, 'text': '<p>If 3rd-party extensions are allowed, then <a href="http://www.google.co.il/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fwww.itu.dk%2Fresearch%2Fc5%2F&amp;ei=H_vTSPmZGZyw0gTK4t2VDQ&amp;usg=AFQjCNEd1FXV-4rROqtPwZ_jDwmW1w5pFA&amp;sig2=ILE99mEc76cQ6g-iRnPgbQ" rel="nofollow noreferrer">C5</a> and <a href="http://www.google.co.il/url?sa=t&amp;source=web&amp;ct=res&amp;cd=2&amp;url=http%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2Fbb648752.aspx&amp;ei=N_vTSPzrComE0QSvwemcDQ&amp;usg=AFQjCNFxZGL9m_QDWlvlkRNOpiLSG_q8bA&amp;sig2=NGJmUpq-jE6kawcvaWWGYQ" rel="nofollow noreferrer">Microsoft CCR</a> (see <a href="http://www.lnbogen.com/MicrosoftCCRCleanWayToWriteParallelCodeInNet.aspx" rel="nofollow noreferrer">this blog post</a> for a quick introduction) are a must-know.</p>\n\n<p>C5 complements .Net\'s somewhat lacking collections library (not Set???), and CCR makes concurrent programming easier (I hear it\'s due to be merged with Parallel Extensions).</p>\n'}, {'answer_id': 105042, 'author': 'Wyzfen', 'author_id': 15261, 'author_profile': 'https://Stackoverflow.com/users/15261', 'pm_score': 6, 'selected': False, 'text': '<p>Dictionary.TryGetValue(K key, out V value)</p>\n\n<p>Works as a check and a get in one. Rather than;</p>\n\n<pre><code>if(dictionary.ContainsKey(key)) \n{\n    value = dictionary[key];\n    ...\n}\n</code></pre>\n\n<p>you can just do;</p>\n\n<pre><code>if(dictionary.TryGetValue(key, out value)) \n{ ... }\n</code></pre>\n\n<p>and the value has been set.</p>\n'}, {'answer_id': 106750, 'author': 'Ray Lu', 'author_id': 11413, 'author_profile': 'https://Stackoverflow.com/users/11413', 'pm_score': 2, 'selected': False, 'text': '<p>I think a lot of people know about pointers in C but are not sure if it works in C#. You can use pointers in C# in an unsafe context:</p>\n\n<pre><code>static void Main()\n{\n    int i;\n    unsafe\n    {               \n        // pointer pi has the address of variable i\n        int* pi = &amp;i; \n        // pointer ppi has the address of variable pi\n        int** ppi = &amp;pi;\n        // ppi(addess of pi) -&gt; pi(addess of i) -&gt; i(0)\n        i = 0;\n        // dereference the pi, i.e. *pi is i\n        Console.WriteLine("i = {0}", *pi); // output: i = 0\n        // since *pi is i, equivalent to i++\n        (*pi)++;\n        Console.WriteLine("i = {0}", *pi); // output: i = 1\n        // since *ppi is pi, one more dereference  *pi is i \n        // equivalent to i += 2\n        **ppi += 2;\n        Console.WriteLine("i = {0}", *pi);// output: i = 3\n    }\n    Console.ReadLine();\n}\n</code></pre>\n'}, {'answer_id': 119648, 'author': 'leppie', 'author_id': 15541, 'author_profile': 'https://Stackoverflow.com/users/15541', 'pm_score': 1, 'selected': False, 'text': '<p>Some ?? weirdness  :)</p>\n\n<pre><code>Delegate target =\n  (target0 = target as CallTargetWithContext0) ??\n  (target1 = target as CallTargetWithContext1) ??\n  (target2 = target as CallTargetWithContext2) ??\n  (target3 = target as CallTargetWithContext3) ??\n  (target4 = target as CallTargetWithContext4) ??\n  (target5 = target as CallTargetWithContext5) ??\n  ((Delegate)(targetN = target as CallTargetWithContextN));\n</code></pre>\n\n<p>Interesting to note the last cast that is needed for some reason. Bug or by design?</p>\n'}, {'answer_id': 121405, 'author': 'axel_c', 'author_id': 20272, 'author_profile': 'https://Stackoverflow.com/users/20272', 'pm_score': 3, 'selected': False, 'text': "<pre><code>System.Diagnostics.Debug.Assert (false);\n</code></pre>\n\n<p>will trigger a popup and allow you to attach a debugger to a running .NET process during execution. Very useful for those times when for some reason you can't directly debug an ASP.NET application.</p>\n"}, {'answer_id': 121470, 'author': 'Flory', 'author_id': 5551, 'author_profile': 'https://Stackoverflow.com/users/5551', 'pm_score': 4, 'selected': False, 'text': '<p>There are operators for performing <a href="http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx" rel="nofollow noreferrer"><code>implicit</code></a> and <a href="http://msdn.microsoft.com/en-us/library/xhbhezf4.aspx" rel="nofollow noreferrer"><code>explicit</code></a> user-defined type conversion between the declared class and one or more arbitrary classes. The <code>implicit</code> operator effectively allows the simulation of overloading the assignement operator, which is possible in languages such as C++ but not C#.</p>\n\n<p>It doesn\'t seem to be a feature one comes across very often, but it is in fact used in the <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_XML" rel="nofollow noreferrer">LINQ to XML</a> (<code>System.Xml.Linq</code>) library, where you can implicitly convert strings to <code>XName</code> objects. Example:</p>\n\n<pre><code>XName tagName = "x:Name";\n</code></pre>\n\n<p>I discovered this feature in this <a href="http://www.codeproject.com/KB/architecture/smip.aspx" rel="nofollow noreferrer">article</a> about how to simulate multiple inheritance in C#.</p>\n'}, {'answer_id': 123701, 'author': 'ZeroBugBounce', 'author_id': 11314, 'author_profile': 'https://Stackoverflow.com/users/11314', 'pm_score': 8, 'selected': False, 'text': '<p><strong>Unions (the C++ shared memory kind) in pure, safe C#</strong></p>\n\n<p>Without resorting to unsafe mode and pointers, you can have class members share memory space in a class/struct.  Given the following class:</p>\n\n<pre><code>[StructLayout(LayoutKind.Explicit)]\npublic class A\n{\n    [FieldOffset(0)]\n    public byte One;\n\n    [FieldOffset(1)]\n    public byte Two;\n\n    [FieldOffset(2)]\n    public byte Three;\n\n    [FieldOffset(3)]\n    public byte Four;\n\n    [FieldOffset(0)]\n    public int Int32;\n}\n</code></pre>\n\n<p>You can modify the values of the byte fields by manipulating the Int32 field and vice-versa.  For example, this program:</p>\n\n<pre><code>    static void Main(string[] args)\n    {\n        A a = new A { Int32 = int.MaxValue };\n\n        Console.WriteLine(a.Int32);\n        Console.WriteLine("{0:X} {1:X} {2:X} {3:X}", a.One, a.Two, a.Three, a.Four);\n\n        a.Four = 0;\n        a.Three = 0;\n        Console.WriteLine(a.Int32);\n    }\n</code></pre>\n\n<p>Outputs this:</p>\n\n<pre><code>2147483647\nFF FF FF 7F\n65535\n</code></pre>\n\n<p>just add\nusing System.Runtime.InteropServices;</p>\n'}, {'answer_id': 140221, 'author': 'Jon Skeet', 'author_id': 22656, 'author_profile': 'https://Stackoverflow.com/users/22656', 'pm_score': 6, 'selected': False, 'text': '<p>A few hidden features I\'ve come across:</p>\n\n<ul>\n<li><code>stackalloc</code> which lets you allocate arrays on the stack</li>\n<li>Anonymous methods with no explicit parameter list, which are implicitly convertible to any delegate type with non-out/ref parameters (very handy for events, as noted in an earlier comment)</li>\n<li>A lot of people aren\'t aware of what events really are (an add/remove pair of methods, like get/set for properties); field-like events in C# really declare both a variable <em>and</em> an event</li>\n<li>The <code>==</code> and <code>!=</code> operators can be overloaded to return types other than <code>bool</code>. Strange but true.</li>\n<li>The query expression translation in C# 3 is really "simple" in some ways - which means you can get it to do some <a href="http://msmvps.com/blogs/jon_skeet/archive/2008/02/29/odd-query-expressions.aspx" rel="nofollow noreferrer">very odd things</a>.</li>\n<li>Nullable types have special boxing behaviour: a null value gets boxed to a null reference, and you can unbox from null to the nullable type too.</li>\n</ul>\n'}, {'answer_id': 149509, 'author': 'Mihai Lazar', 'author_id': 4204, 'author_profile': 'https://Stackoverflow.com/users/4204', 'pm_score': 4, 'selected': False, 'text': '<p>One feature that I only learned about here on Stack Overflow was the ability to set an attribute on the return parameter. </p>\n\n<pre><code>[AttributeUsage( AttributeTargets.ReturnValue )]\npublic class CuriosityAttribute:Attribute\n{\n}\n\npublic class Bar\n{\n    [return: Curiosity]\n    public Bar ReturnANewBar()\n    {\n        return new Bar();\n    }\n}\n</code></pre>\n\n<p>This was truly a hidden feature for me :-)</p>\n'}, {'answer_id': 157242, 'author': 'dariom', 'author_id': 12389, 'author_profile': 'https://Stackoverflow.com/users/12389', 'pm_score': 3, 'selected': False, 'text': '<p>String interning. This is one that I haven\'t seen come up in this discussion yet. It\'s a little obscure, but in certain conditions it can be useful.</p>\n\n<p>The CLR keeps a table of references to literal strings (and programmatically interned strings). If you use the same string in several places in your code it will be stored once in the table. This can ease the amount of memory required for allocating strings.</p>\n\n<p>You can test if a string is interned by using <a href="http://msdn.microsoft.com/en-us/library/system.string.isinterned.aspx" rel="nofollow noreferrer">String.IsInterned(string)</a> and you can intern a string using <a href="http://msdn.microsoft.com/en-us/library/system.string.intern.aspx" rel="nofollow noreferrer">String.Intern(string)</a>.</p>\n\n<p><strong>Note:</strong> The CLR can hold a reference to an interned string after application or even AppDomain end. See the MSDN documentation for details.</p>\n'}, {'answer_id': 165795, 'author': 'Tim Jarvis', 'author_id': 10387, 'author_profile': 'https://Stackoverflow.com/users/10387', 'pm_score': 6, 'selected': False, 'text': '<p>The params keyword, i.e.</p>\n\n<pre><code>public void DoSomething(params string[] theStrings)\n{\n  foreach(string s in theStrings)\n  {\n    // Something with the Strings…\n  }\n}\n</code></pre>\n\n<p>Called like</p>\n\n<pre><code>DoSomething(“The”, “cat”, “sat”, “on”, “the” ,”mat”);\n</code></pre>\n'}, {'answer_id': 165845, 'author': 'tsilb', 'author_id': 11112, 'author_profile': 'https://Stackoverflow.com/users/11112', 'pm_score': 4, 'selected': False, 'text': '<p>Labeling my endregions...</p>\n\n<pre><code>#region stuff1\n #region stuff1a\n //...\n #endregion stuff1a\n#endregion stuff1\n</code></pre>\n'}, {'answer_id': 174763, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': '<p>I picked this one up when using <a href="http://www.jetbrains.com/resharper/" rel="nofollow noreferrer">ReSharper</a>:</p>\n\n<p>Implicit Method Group Conversion </p>\n\n<pre><code>//If given this:\nvar myStrings = new List&lt;string&gt;(){"abc","def","xyz"};\n//Then this:\nmyStrings.ForEach(s =&gt; Console.WriteLine(s));\n//Is equivalent to this:\nmyStrings.ForEach(Console.WriteLine);\n</code></pre>\n\n<p>See "<a href="http://blog.opennetcf.com/ncowburn/2007/03/23/ImplicitMethodGroupConversionInC.aspx" rel="nofollow noreferrer">Implicit Method Group Conversion in C#</a>" for more.</p>\n'}, {'answer_id': 176231, 'author': 'Patrick Szalapski', 'author_id': 7453, 'author_profile': 'https://Stackoverflow.com/users/7453', 'pm_score': 3, 'selected': False, 'text': '<p>Instead of using int.TryParse() or Convert.ToInt32(), I like having a static integer parsing function that returns null when it can\'t parse.  Then I can use ?? and the ternary operator together to more clearly ensure my declaration and initialization are all done on one line in a easy-to-understand way.   </p>\n\n<pre><code>public static class Parser {\n    public static int? ParseInt(string s) {\n        int result;\n        bool parsed = int.TryParse(s, out result);\n        if (parsed) return result;\n        else return null;\n    }\n    // ...\n}\n</code></pre>\n\n<p>This is also good to avoid duplicating the left side of an assignment, but even better to avoid duplicating long calls on the right side of an assignment, such as a database calls in the following example.  Instead of ugly if-then trees (which I run into often):</p>\n\n<pre><code>int x = 0;\nYourDatabaseResultSet data = new YourDatabaseResultSet();\nif (cond1)\n    if (int.TryParse(x_input, x)){\n        data = YourDatabaseAccessMethod("my_proc_name", 2, x);\n    }\n    else{\n        x = -1;\n        // do something to report "Can\'t Parse"    \n    }\n}\nelse {\n    x = y;\n    data = YourDatabaseAccessMethod("my_proc_name", \n       new SqlParameter("@param1", 2),\n       new SqlParameter("@param2", x));\n}\n</code></pre>\n\n<p>You can do:</p>\n\n<pre><code>int x = cond1 ? (Parser.ParseInt(x_input) ?? -1) : y;\nif (x &gt;= 0)  data = YourDatabaseAccessMethod("my_proc_name", \n    new SqlParameter("@param1", 2),\n    new SqlParameter("@param2", x));\n</code></pre>\n\n<p>Much cleaner and easier to understand</p>\n'}, {'answer_id': 181714, 'author': 'GvS', 'author_id': 11492, 'author_profile': 'https://Stackoverflow.com/users/11492', 'pm_score': 5, 'selected': False, 'text': '<p>The <a href="http://msdn.microsoft.com/en-us/library/system.environment.userinteractive.aspx" rel="nofollow noreferrer">Environment.UserInteractive</a> property. </p>\n\n<blockquote>\n  <p>The UserInteractive property reports\n  false for a Windows process or a\n  service like IIS that runs without a\n  user interface. If this property is\n  false, do not display modal dialogs or\n  message boxes because there is no\n  graphical user interface for the user\n  to interact with.</p>\n</blockquote>\n'}, {'answer_id': 189100, 'author': 'Scott McKenzie', 'author_id': 26625, 'author_profile': 'https://Stackoverflow.com/users/26625', 'pm_score': 2, 'selected': False, 'text': '<p>ContextBoundObject</p>\n\n<p>Not so much a C# thing as a .NET thing. It\'s another way of achieving DI although it can be hardwork. And you have to inherit from it which can be off putting.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.contextboundobject.aspx</a></p>\n\n<p>I\'ve used it to add logging when I decorate a class/method with a custom logging attribute.</p>\n'}, {'answer_id': 192127, 'author': 'IgorM', 'author_id': 17823, 'author_profile': 'https://Stackoverflow.com/users/17823', 'pm_score': 5, 'selected': False, 'text': "<p>Full access to the call stack:</p>\n\n<pre><code>public static void Main()\n{\n  StackTrace stackTrace = new StackTrace();           // get call stack\n  StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)\n\n  // write call stack method names\n  foreach (StackFrame stackFrame in stackFrames)\n  {\n    Console.WriteLine(stackFrame.GetMethod().Name);   // write method name\n  }\n}\n</code></pre>\n\n<p>So, if you'll take the first one - you know what function you are in. If you're creating a helper tracing function - take one before the last one - you'll know your caller.</p>\n"}, {'answer_id': 195097, 'author': 'sbeskur', 'author_id': 10446, 'author_profile': 'https://Stackoverflow.com/users/10446', 'pm_score': 3, 'selected': False, 'text': '<p>I find this technique interesting while working with linqxml:</p>\n\n<pre><code>public bool GetFooSetting(XElement ndef){\n   return (bool?)ndef.Element("MyBoolSettingValue") ?? true;\n}\n</code></pre>\n\n<p>as opposed to:</p>\n\n<pre><code>public bool GetFooSetting(XElement ndef){\n   return ndef.Element("MyBoolSettingValue") != null ? bool.Parse(ndef.Element("MyBoolSettingValue") ) : true;\n}\n</code></pre>\n'}, {'answer_id': 199247, 'author': 'Jan Bannister', 'author_id': 460845, 'author_profile': 'https://Stackoverflow.com/users/460845', 'pm_score': 7, 'selected': False, 'text': '<p>If you want to exit your program without calling any finally blocks or finalizers use <a href="http://msdn.microsoft.com/en-us/library/ms131100.aspx" rel="nofollow noreferrer">FailFast</a>:</p>\n\n<pre><code>Environment.FailFast()\n</code></pre>\n'}, {'answer_id': 199257, 'author': 'Jan Bannister', 'author_id': 460845, 'author_profile': 'https://Stackoverflow.com/users/460845', 'pm_score': 2, 'selected': False, 'text': '<pre><code>double dSqrd = Math.Pow(d,2.0); \n</code></pre>\n\n<p>is more accurate than </p>\n\n<pre><code>double dSqrd = d * d; // Here we can lose precision\n</code></pre>\n'}, {'answer_id': 199269, 'author': 'Jan Bannister', 'author_id': 460845, 'author_profile': 'https://Stackoverflow.com/users/460845', 'pm_score': 3, 'selected': False, 'text': '<p>You can switch on string!</p>\n\n<pre><code>switch(name)\n{\n  case "Dave":\n    return true;\n  case "Bob":\n    return false;\n  default:\n    throw new ApplicationException();\n}\n</code></pre>\n\n<p>Very handy! and a lot cleaner than a bunch of if-else statements</p>\n'}, {'answer_id': 212905, 'author': 'Cristian Libardo', 'author_id': 16526, 'author_profile': 'https://Stackoverflow.com/users/16526', 'pm_score': 6, 'selected': False, 'text': '<p>Just learned, anonymous types can infer property names from the variable name:</p>\n\n<pre><code>string hello = "world";\nvar o = new { hello };\nConsole.WriteLine(o.hello);\n</code></pre>\n'}, {'answer_id': 214951, 'author': 'Mike Two', 'author_id': 23659, 'author_profile': 'https://Stackoverflow.com/users/23659', 'pm_score': 6, 'selected': False, 'text': '<p>More of a runtime feature, but I recently learned that there are two garbage collectors. The workstation gc and the server gc. Workstation is the default on client versions of windows, but server is much faster on multicore machines.</p>\n\n<pre><code>\n&lt;configuration&gt;\n   &lt;runtime&gt;\n      &lt;gcServer enabled="true"/&gt;\n   &lt;/runtime&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>Be careful. The server gc requires more memory.</p>\n'}, {'answer_id': 223087, 'author': 'Ian Andrews', 'author_id': 2382102, 'author_profile': 'https://Stackoverflow.com/users/2382102', 'pm_score': 2, 'selected': False, 'text': '<p>This may be pretty basic to database application developers, but it took me a while to realize that null is not the same as DBNull.value.  </p>\n\n<p>You have to use DBNull.value when you want to see if a value from a database record is null.</p>\n'}, {'answer_id': 236173, 'author': 'splattne', 'author_id': 6461, 'author_profile': 'https://Stackoverflow.com/users/6461', 'pm_score': 3, 'selected': False, 'text': '<h2>Object.ReferenceEquals Method</h2>\n\n<p>Determines whether the specified Object instances are the same instance.</p>\n\n<p><strong>Parameters:</strong></p>\n\n<ul>\n<li>objA: System.Object - The first Object to compare. </li>\n<li>objB: System.Object - The second Object to compare. </li>\n</ul>\n\n<p><strong>Example:</strong></p>\n\n<pre><code> object o = null;\n object p = null;\n object q = new Object();\n\n Console.WriteLine(Object.ReferenceEquals(o, p));\n p = q;\n Console.WriteLine(Object.ReferenceEquals(p, q));\n Console.WriteLine(Object.ReferenceEquals(o, p));\n</code></pre>\n\n<p><strong>Difference to "==" and ".Equals":</strong></p>\n\n<p>Basically, Equals() tests of object A has the same content as object B.</p>\n\n<p>The method System.Object.ReferenceEquals() always compares references.\nAlthough a class can provide its own behavior for the equality operator\n(below), that re-defined operator isn\'t invoked if the operator is called\nvia a reference to System.Object. </p>\n\n<p>For strings there isn\'t really a difference, because both == and Equals have been overriden to compare the content of the string.</p>\n\n<p>See also <a href="https://stackoverflow.com/questions/73713/how-do-i-check-for-nulls-in-an-operator-overload-without-infinite-recursion#73732">this answer</a> to another question ("How do I check for nulls in an ‘==’ operator overload without infinite recursion?").</p>\n'}, {'answer_id': 238462, 'author': 'Dmitri Nesteruk', 'author_id': 9476, 'author_profile': 'https://Stackoverflow.com/users/9476', 'pm_score': 7, 'selected': False, 'text': '<p>Mixins. Basically, if you want to add a feature to several classes, but cannot use one base class for all of them, get each class to implement an interface (with no members). Then, write an extension method <strong>for the interface</strong>, i.e.</p>\n\n<pre><code>public static DeepCopy(this IPrototype p) { ... }\n</code></pre>\n\n<p>Of course, some clarity is sacrificed. But it works!</p>\n'}, {'answer_id': 256013, 'author': 'dviljoen', 'author_id': 29021, 'author_profile': 'https://Stackoverflow.com/users/29021', 'pm_score': 2, 'selected': False, 'text': '<p>ThreadStaticAttribute is a favorite of mine.  Also, NonSerializableAttribute is useful.  (Can you tell I do a lot of server stuff using remoting?)</p>\n'}, {'answer_id': 258982, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>The generic event handler:</p>\n\n<pre><code>public event EventHandler&lt;MyEventArgs&gt; MyEvent;\n</code></pre>\n\n<p>This way you don't have to declare your own delegates all the time,</p>\n"}, {'answer_id': 259028, 'author': 'Dan Fleet', 'author_id': 7470, 'author_profile': 'https://Stackoverflow.com/users/7470', 'pm_score': 2, 'selected': False, 'text': '<p>Just learned the joys of <code>[UnmanagedFunctionPointerAttribute(CallingConvention.CDecl)]</code> from trying to interface with an unmanaged C++ function library that defined callbacks without __stdcall.</p>\n'}, {'answer_id': 259134, 'author': 'Gavin Miller', 'author_id': 33226, 'author_profile': 'https://Stackoverflow.com/users/33226', 'pm_score': 3, 'selected': False, 'text': "<p>I didn't discover - for almost a year - that Strongly Typed DataRows contain an Is[ColumnName]Null() method.</p>\n\n<p>For example:</p>\n\n<pre><code>Units.UnitsDataTable dataTable = new Units.UnitsDataTable();\n\nforeach (Units.UnitsRow row in dataTable.Rows)\n{\n    if (row.IsPrimaryKeyNull())\n        //....\n\n    if (row.IsForeignKeyNull())\n        //....\n}\n</code></pre>\n"}, {'answer_id': 263868, 'author': 'Cohen', 'author_id': 34474, 'author_profile': 'https://Stackoverflow.com/users/34474', 'pm_score': 3, 'selected': False, 'text': "<p>Math.Max and Min to check boundaries:\nI 've seen this in a lot of code:</p>\n\n<pre><code>if (x &lt; lowerBoundary) \n{\n   x = lowerBoundary;\n}\n</code></pre>\n\n<p>I find this smaller, cleaner and more readable:</p>\n\n<pre><code>x = Math.Max(x, lowerBoundary);\n</code></pre>\n\n<p>Or you can also use a ternary operator:</p>\n\n<pre><code>x = ( x &lt; lowerBoundary) ? lowerBoundary : x;\n</code></pre>\n"}, {'answer_id': 263883, 'author': 'Cohen', 'author_id': 34474, 'author_profile': 'https://Stackoverflow.com/users/34474', 'pm_score': 4, 'selected': False, 'text': '<p>Something I missed for a long time:\nyou can compare strings with </p>\n\n<pre><code>"string".equals("String", StringComparison.InvariantCultureIgnoreCase)\n</code></pre>\n\n<p>instead of doing: </p>\n\n<pre><code>"string".ToLower() == "String".ToLower();\n</code></pre>\n'}, {'answer_id': 270430, 'author': 'Dmitri Nesteruk', 'author_id': 9476, 'author_profile': 'https://Stackoverflow.com/users/9476', 'pm_score': 3, 'selected': False, 'text': '<p>Mixins are a nice feature. Basically, mixins let you have concrete code for an interface instead of a class. Then, just implement the interface in a bunch of classes, and you automatically get mixin functionality. For example, to mix in deep copying into several classes, define an interface</p>\n\n<pre><code>internal interface IPrototype&lt;T&gt; { }\n</code></pre>\n\n<p>Add functionality for this interface</p>\n\n<pre><code>internal static class Prototype\n{\n  public static T DeepCopy&lt;T&gt;(this IPrototype&lt;T&gt; target)\n  {\n    T copy;\n    using (var stream = new MemoryStream())\n    {\n      var formatter = new BinaryFormatter();\n      formatter.Serialize(stream, (T)target);\n      stream.Seek(0, SeekOrigin.Begin);\n      copy = (T) formatter.Deserialize(stream);\n      stream.Close();\n    }\n    return copy;\n  }\n}\n</code></pre>\n\n<p>Then implement interface in any type to get a mixin.</p>\n'}, {'answer_id': 292258, 'author': 'Bryan Watts', 'author_id': 37815, 'author_profile': 'https://Stackoverflow.com/users/37815', 'pm_score': 2, 'selected': False, 'text': '<p>ViewState getters can be one-liners.</p>\n\n<p><strong>Using a default value:</strong></p>\n\n<pre><code>public string Caption\n{\n    get { return (string) (ViewState["Caption"] ?? "Foo"); }\n    set { ViewState["Caption"] = value; }\n}\n\npublic int Index\n{\n    get { return (int) (ViewState["Index"] ?? 0); }\n    set { ViewState["Index"] = value; }\n}\n</code></pre>\n\n<p><strong>Using null as the default:</strong></p>\n\n<pre><code>public string Caption\n{\n    get { return (string) ViewState["Caption"]; }\n    set { ViewState["Caption"] = value; }\n}\n\npublic int? Index\n{\n    get { return (int?) ViewState["Index"]; }\n    set { ViewState["Index"] = value; }\n}\n</code></pre>\n\n<p>This works for anything backed by a dictionary.</p>\n'}, {'answer_id': 295174, 'author': 'Eyvind', 'author_id': 25746, 'author_profile': 'https://Stackoverflow.com/users/25746', 'pm_score': 3, 'selected': False, 'text': "<p>Regarding <code>foreach</code>: It does not use 'duck typing', as duck typing IMO refers to a runtime check. It uses <em>structural type checking</em> (as opposed to nominal) at compile time to check for the required method in the type.</p>\n"}, {'answer_id': 298424, 'author': 'Enes', 'author_id': 2921654, 'author_profile': 'https://Stackoverflow.com/users/2921654', 'pm_score': 1, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/169276/is-the-region-directive-really-useful-in-net#287438">Here is a TIP</a> of how you can use #Region directive to document your code.</p>\n'}, {'answer_id': 299153, 'author': 'Bryan Watts', 'author_id': 37815, 'author_profile': 'https://Stackoverflow.com/users/37815', 'pm_score': 3, 'selected': False, 'text': '<p>(I just used this one) Set a field null and return it without an intermediate variable:</p>\n\n<pre><code>try\n{\n    return _field;\n}\nfinally\n{\n    _field = null;\n}\n</code></pre>\n'}, {'answer_id': 299173, 'author': 'Rytmis', 'author_id': 266, 'author_profile': 'https://Stackoverflow.com/users/266', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/aa664591(VS.71).aspx" rel="nofollow noreferrer">Explicit interface member implementation</a>, wherein an interface member is implemented, but hidden unless the instance is cast to the interface type. </p>\n'}, {'answer_id': 299236, 'author': 'Bryan Watts', 'author_id': 37815, 'author_profile': 'https://Stackoverflow.com/users/37815', 'pm_score': 5, 'selected': False, 'text': "<p>On-demand field initialization in one line:</p>\n\n<pre><code>public StringBuilder Builder\n{\n    get { return _builder ?? (_builder = new StringBuilder()); }\n}\n</code></pre>\n\n<p>I'm not sure how I feel about C# supporting assignment expressions, but hey, it's there :-)</p>\n"}, {'answer_id': 300100, 'author': 'open-collar', 'author_id': 21686, 'author_profile': 'https://Stackoverflow.com/users/21686', 'pm_score': 4, 'selected': False, 'text': "<p>Several people have mentioned <em>using</em> blocks, but I think they are much more useful than people have realised.   Think of them as the poor man's AOP tool.  I have a host of simple objects that capture state in the constructor and then restore it in the <em>Dispose()</em> method.  That allows me to wrap a piece of functionality in a <em>using</em> block and be sure that the state is restored at the end.  For example:</p>\n\n<pre><code>using(new CursorState(this, BusyCursor));\n{\n    // Do stuff\n}\n</code></pre>\n\n<p><em>CursorState</em> captures the current cursor being used by form, then sets the form to use the cursor supplied.  At the end it restores the original cursor.  I do loads of things like this, for example capturing the selections and current row on a grid before refreshing and so on.</p>\n"}, {'answer_id': 302484, 'author': 'Tor Haugen', 'author_id': 32050, 'author_profile': 'https://Stackoverflow.com/users/32050', 'pm_score': 4, 'selected': False, 'text': '<p>You can use any Unicode character in C# names, for example:</p>\n\n<pre><code>public class MyClass\n{\n    public string Hårføner()\n    {\n        return "Yes, it works!";\n    }\n}\n</code></pre>\n\n<p>You can even use Unicode escapes. This one is equivalent to the above:</p>\n\n<pre><code>public class MyClass\n{\n    public string H\\u00e5rføner()\n    {\n        return "Yes, it (still) works!";\n    }\n}\n</code></pre>\n'}, {'answer_id': 302602, 'author': 'MysticSlayer', 'author_id': 28139, 'author_profile': 'https://Stackoverflow.com/users/28139', 'pm_score': 4, 'selected': False, 'text': '<p>What about using this:</p>\n\n<pre><code>#if DEBUG\n            Console.Write("Debugging");\n#else\n            Console.Write("Final");\n#endif\n</code></pre>\n\n<p>When you have your solution compiled with DEBUG defined it will output "Debugging".</p>\n\n<p>If your compile is set to Release it will write "Final".</p>\n'}, {'answer_id': 312756, 'author': 'Gregor', 'author_id': 26153, 'author_profile': 'https://Stackoverflow.com/users/26153', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Framework Feature</strong></p>\n\n<p>I don\'t know but I was quite suprised about <a href="http://msdn.microsoft.com/de-de/library/system.windows.forms.visualstyles.visualstylerenderer(VS.85).aspx" rel="nofollow noreferrer">VisualStyleRenderer</a> and the whole <a href="http://msdn.microsoft.com/de-de/library/system.windows.forms.visualstyles(VS.85).aspx" rel="nofollow noreferrer">System.Windows.Forms.VisualStyles-Namespace</a>. Pretty cool!</p>\n'}, {'answer_id': 314065, 'author': 'Richard Ev', 'author_id': 39709, 'author_profile': 'https://Stackoverflow.com/users/39709', 'pm_score': 3, 'selected': False, 'text': "<p><code>IEnumerable</code>'s <code>SelectMany</code>, which flattens a list of lists into a single list. Let's say I have a list of <code>Orders</code>, and each <code>Order</code> has a list of <code>LineItems</code> on that order.</p>\n\n<p>I want to know the total number of <code>LineItems</code> sold... </p>\n\n<pre><code>int totalItems = Orders.Select(o =&gt; o.LineItems).SelectMany(i =&gt; i).Sum();\n</code></pre>\n"}, {'answer_id': 319182, 'author': 'Rob', 'author_id': 34224, 'author_profile': 'https://Stackoverflow.com/users/34224', 'pm_score': 3, 'selected': False, 'text': '<p>This isn\'t a C# specific type, but I just found the ISurrogateSelector and ISerializationSurrogate interfaces --</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx</a></p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.runtime.serialization.isurrogateselector.aspx</a></p>\n\n<p>Using these in conjunction with the BinaryFormatter allows for non-serializable objects to be serialized via the implementation of a surrogate class.  The surrogate pattern is well-understood in computer science, particularly when dealing with the problem of serialization.  I think that this implementation is just tucked away as a parameter of the constructor to BinaryFormatter, and that\'s too bad.</p>\n\n<p>Still - VERY hidden. :)</p>\n'}, {'answer_id': 336237, 'author': 'Phillip Ngan', 'author_id': 41410, 'author_profile': 'https://Stackoverflow.com/users/41410', 'pm_score': 4, 'selected': False, 'text': '<p>The delegate syntax have evolved over successive versions of C#, but I still find them difficult to remember. Fortunately the <code>Action&lt;&gt;</code> and <code>Func&lt;&gt;</code> delegates are easy to remember.</p>\n\n<p>For example:</p>\n\n<ul>\n<li><code>Action&lt;int&gt;</code> is a delegate method that takes a single int argument and returns void.</li>\n<li><code>Func&lt;int&gt;</code>  is a delegate method that takes no arguments and returns an int.</li>\n<li><code>Func&lt;int, bool&gt;</code> is a delegate method that takes a single int argument and returns a bool.</li>\n</ul>\n\n<p>These features were introduced in version 3.5 of the .NET framework.</p>\n'}, {'answer_id': 343526, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>One great class I like is <code>System.Xml.XmlConvert</code> which can be used to read values from xml tag.  Especially, if I am reading a boolean value from xml attribute or element, I use </p>\n\n<pre><code>bool myFlag  = System.Xml.XmlConvert.ToBoolean(myAttribute.Value);\n</code></pre>\n\n<p>Note: since boolean type in xml accepts 1 and 0 in addition to "true" and "false" as valid values, using string comparison in this case is error-prone.</p>\n'}, {'answer_id': 355991, 'author': 'Binoj Antony', 'author_id': 33015, 'author_profile': 'https://Stackoverflow.com/users/33015', 'pm_score': 6, 'selected': False, 'text': '<p>Other underused operators are <code>checked</code> and <code>unchecked</code>:</p>\n\n<pre><code>short x = 32767;   // 32767 is the max value for short\nshort y = 32767;\nint z1 =  checked((short)(x + y));   //will throw an OverflowException\nint z2 =  unchecked((short)(x + y)); // will return -2\nint z3 =  (short)(x + y);            // will return -2\n</code></pre>\n'}, {'answer_id': 365801, 'author': 'Binoj Antony', 'author_id': 33015, 'author_profile': 'https://Stackoverflow.com/users/33015', 'pm_score': 3, 'selected': False, 'text': '<p>To call the base class constructor just put base() inline with the constructor.<br />\nTo call the base class method you can just put base.MethodName() inside the derived class method</p>\n\n<pre><code>class ClassA \n{\n  public ClassA(int a)\n  {\n    //Do something\n  }\n\n  public void Method1()\n  {\n     //Do Something\n  }\n}\n\nclass ClassB : ClassA\n{\n  public ClassB(int a) : base(a) // calling the base class constructor\n  {\n    //Do something\n  }\n\n  public void Method2()\n  {\n    base.Method1();               // calling the base class method\n  }\n}\n</code></pre>\n\n<p>Of course you can call the methods of the base class by just saying <code>base.MethodName()</code></p>\n'}, {'answer_id': 368625, 'author': 'amazedsaint', 'author_id': 45956, 'author_profile': 'https://Stackoverflow.com/users/45956', 'pm_score': 3, 'selected': False, 'text': '<p><strong>dynamic keyword in C# 4.0</strong></p>\n\n<p>You can use dynamic keyword, if you want your method calls to be resolved only at the runtime. </p>\n\n<pre><code>dynamic invoker=new DynamicInvoker();\ndynamic result1=invoker.MyMethod1();\ndynamic result2=invoker.MyMethod2();\n</code></pre>\n\n<p>Here I\'m implementing a dynamic invoker.</p>\n\n<pre><code>public class DynamicInvoker : IDynamicObject\n    {\n        public MetaObject GetMetaObject\n              (System.Linq.Expressions.Expression parameter)\n        {\n            return new DynamicReaderDispatch (parameter);\n        }\n    }\n\n    public class DynamicDispatcher : MetaObject\n    {\n        public DynamicDispatcher (Expression parameter) \n                   : base(parameter, Restrictions.Empty){ }\n\n        public override MetaObject Call(CallAction action, MetaObject[] args)\n        {\n            //You\'ll get MyMethod1 and MyMethod2 here (and what ever you call)\n            Console.WriteLine("Logic to invoke Method \'{0}\'", action.Name);\n            return this; //Return a meta object\n        }\n    }\n</code></pre>\n'}, {'answer_id': 370561, 'author': 'Rinat Abdullin', 'author_id': 47366, 'author_profile': 'https://Stackoverflow.com/users/47366', 'pm_score': 4, 'selected': False, 'text': '<p>Ability to use LINQ Expressions to perform strongly-typed reflection:</p>\n\n<pre><code>static void Main(string[] args)\n{\n  var domain = "matrix";\n  Check(() =&gt; domain);\n  Console.ReadLine();\n}\n\nstatic void Check&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; expr)\n{\n  var body = ((MemberExpression)expr.Body);\n  Console.WriteLine("Name is: {0}", body.Member.Name);\n  Console.WriteLine("Value is: {0}", ((FieldInfo)body.Member)\n   .GetValue(((ConstantExpression)body.Expression).Value));\n}\n\n// output:\n// Name is: \'domain\'\n// Value is: \'matrix\'\n</code></pre>\n\n<p>More details are available at <a href="http://rabdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html" rel="nofollow noreferrer">How to Find Out Variable or Parameter Name in C#?</a></p>\n'}, {'answer_id': 372964, 'author': 'Steven Behnke', 'author_id': 42588, 'author_profile': 'https://Stackoverflow.com/users/42588', 'pm_score': 3, 'selected': False, 'text': '<p>This isn\'t a C# specific feature but it is an addon that I find very useful.  It is called the Resource Refactoring Tool.  It allows you to right click on a literal string and extract it into a resource file.  It will search the code and find any other literal strings that match and replace it with the same resource from the Resx file.</p>\n\n<p><a href="http://www.codeplex.com/ResourceRefactoring" rel="nofollow noreferrer">http://www.codeplex.com/ResourceRefactoring</a></p>\n'}, {'answer_id': 388760, 'author': 'Moran Helman', 'author_id': 1409636, 'author_profile': 'https://Stackoverflow.com/users/1409636', 'pm_score': 3, 'selected': False, 'text': '<p>TrueForAll Method of <code>List&lt;T&gt;</code> :</p>\n\n<pre><code>List&lt;int&gt; s = new List&lt;int&gt; { 6, 1, 2 };\n\nbool a = s.TrueForAll(p =&gt; p &gt; 0);\n</code></pre>\n'}, {'answer_id': 391966, 'author': 'Michael Meadows', 'author_id': 7643, 'author_profile': 'https://Stackoverflow.com/users/7643', 'pm_score': 5, 'selected': False, 'text': '<h2>Closures</h2>\n\n<p>Since anonymous delegates were added to 2.0, we have been able to develop closures. They are rarely used by programmers but provide great benefits such as immediate code reuse. Consider this piece of code:</p>\n\n<pre><code>bool changed = false;\n\nif (model.Prop1 != prop1)\n{\n    changed = true;\n    model.Prop1 = prop1;\n}\nif (model.Prop2 != prop2)\n{\n    changed = true;\n    model.Prop2 = prop2;\n}\n// ... etc. \n</code></pre>\n\n<p>Note that the if-statements above perform similar pieces of code with the exception of one line of code, i.e. setting different properties. This can be shortened with the following, where the varying line of code is entered as a parameter to an <code>Action</code> object, appropriately named <code>setAndTagChanged</code>:</p>\n\n<pre><code>bool changed = false;\nAction&lt;Action&gt; setAndTagChanged = (action) =&gt; \n{ \n    changed = true; \n    action(); \n};\n\nif (model.Prop1 != prop1) setAndTagChanged(() =&gt; model.Prop1 = prop1);\nif (model.Prop2 != prop2) setAndTagChanged(() =&gt; model.Prop2 = prop2);\n</code></pre>\n\n<p>In the second case, the closure allows you to scope the <code>change</code> variable in your lambda, which is a concise way to approach this problem.</p>\n\n<p>An alternate way is to use another unused feature, the "or equal" binary assignment operator. The following code shows how:</p>\n\n<pre><code>private bool conditionalSet(bool condition, Action action)\n{\n    if (condition) action();\n    return condition;\n}\n\n// ...\n\nbool changed = false;\nchanged |= conditionalSet(model.Prop1 == prop1, () =&gt; model.Prop1 = prop1);\nchanged |= conditionalSet(model.Prop2 == prop2, () =&gt; model.Prop2 = prop2);\n</code></pre>\n'}, {'answer_id': 399297, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>I call this AutoDebug because you can drop right into debug where and when you need based on a bool value which could also be stored as a project user setting as well.</p>\n\n<p>Example:</p>\n\n<pre><code>//Place at top of your code\npublic UseAutoDebug = true;\n\n\n//Place anywhere in your code including catch areas in try/catch blocks\nDebug.Assert(!this.UseAutoDebug);\n</code></pre>\n\n<p>Simply place the above in try/catch blocks or other areas of your code and set UseAutoDebug to true or false and drop into debug anytime you wish for testing.</p>\n\n<p>You can leave this code in place and toggle this feature on and off when testing, You can also save it as a Project Setting, and manually change it after deployment to get additional bug information from users when/if needed as well.</p>\n\n<p>You can see a functional and working example of using this technique in this Visual Studio C# Project Template here, where it is used heavily:</p>\n\n<p><a href="http://code.msdn.microsoft.com/SEHE" rel="nofollow noreferrer">http://code.msdn.microsoft.com/SEHE</a></p>\n'}, {'answer_id': 405088, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 4, 'selected': False, 'text': '<p><strong>C# 3.0\'s LINQ query comprehensions are full-blown monadic comprehensions</strong> <em>a la</em> Haskell (in fact they were designed by one of Haskell\'s designers). They will work for any generic type that follows the "LINQ pattern" and allows you to write in a pure monadic functional style, which means that all of your variables are immutable (as if the only variables you used were <code>IDisposable</code>s and <code>IEnumerable</code>s in <em>using</em> and <em>foreach</em> statements). This is helpful for keeping variable declarations close to where they\'re used and making sure that all side-effects are explicitly declared, if there are any at all.</p>\n\n<pre><code> interface IFoo&lt;T&gt;\n  { T Bar {get;}\n  }\n\n class MyFoo&lt;T&gt; : IFoo&lt;T&gt; \n  { public MyFoo(T t) {Bar = t;}\n    public T Bar {get; private set;} \n  }\n\n static class Foo \n  { public static IFoo&lt;T&gt; ToFoo&lt;T&gt;(this T t) {return new MyFoo&lt;T&gt;(t);}\n\n    public static void Do&lt;T&gt;(this T t, Action&lt;T&gt; a) { a(t);}\n\n    public static IFoo&lt;U&gt; Select&lt;T,U&gt;(this IFoo&lt;T&gt; foo, Func&lt;T,U&gt; f) \n     { return f(foo.Bar).ToFoo();\n     }\n  }\n\n /* ... */\n\n using (var file = File.OpenRead("objc.h"))\n { var x = from f in file.ToFoo()\n           let s = new Scanner(f)\n           let p = new Parser {scanner = s}\n           select p.Parse();\n\n   x.Do(p =&gt; \n    { /* drop into imperative code to handle file \n         in Foo monad if necessary */      \n    });\n\n }\n</code></pre>\n'}, {'answer_id': 407325, 'author': 'hugoware', 'author_id': 17091, 'author_profile': 'https://Stackoverflow.com/users/17091', 'pm_score': 5, 'selected': False, 'text': "<p>I'd say using certain system classes for extension methods is very handy, for example System.Enum, you can do something like below...</p>\n\n<pre><code>[Flags]\npublic enum ErrorTypes : int {\n    None = 0,\n    MissingPassword = 1,\n    MissingUsername = 2,\n    PasswordIncorrect = 4\n}\n\npublic static class EnumExtensions {\n\n    public static T Append&lt;T&gt; (this System.Enum type, T value) where T : struct\n    {\n        return (T)(ValueType)(((int)(ValueType) type | (int)(ValueType) value));\n    }\n\n    public static T Remove&lt;T&gt; (this System.Enum type, T value) where T : struct\n    {\n        return (T)(ValueType)(((int)(ValueType)type &amp; ~(int)(ValueType)value));\n    }\n\n    public static bool Has&lt;T&gt; (this System.Enum type, T value) where T : struct\n    {\n        return (((int)(ValueType)type &amp; (int)(ValueType)value) == (int)(ValueType)value);\n    }\n\n}\n\n...\n\n//used like the following...\n\nErrorTypes error = ErrorTypes.None;\nerror = error.Append(ErrorTypes.MissingUsername);\nerror = error.Append(ErrorTypes.MissingPassword);\nerror = error.Remove(ErrorTypes.MissingUsername);\n\n//then you can check using other methods\nif (error.Has(ErrorTypes.MissingUsername)) {\n    ...\n}\n</code></pre>\n\n<p>This is just an example of course - the methods could use a little more work...</p>\n"}, {'answer_id': 475559, 'author': 'JohnOpincar', 'author_id': 16245, 'author_profile': 'https://Stackoverflow.com/users/16245', 'pm_score': 3, 'selected': False, 'text': '<p>You can have generic methods in a non-generic class.</p>\n'}, {'answer_id': 498292, 'author': 'Andrew Peters', 'author_id': 608, 'author_profile': 'https://Stackoverflow.com/users/608', 'pm_score': 3, 'selected': False, 'text': '<p>Cool trick to emulate functional "wildcard" arguments (like \'_\' in Haskell) when using lambdas:</p>\n\n<pre><code>(_, b, __) =&gt; b.DoStuff();  // only interested in b here\n</code></pre>\n'}, {'answer_id': 508371, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Only for reference - enum binary operations using the extension method.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Linq.Expressions;\n\nnamespace BinaryOpGenericTest\n{\n    [Flags]\n    enum MyFlags\n    {\n        A = 1,\n        B = 2,\n        C = 4\n\n    }\n\n    static class EnumExtensions\n    {\n        private static Dictionary&lt;Type, Delegate&gt; m_operations = new Dictionary&lt;Type, Delegate&gt;();\n\n        public static bool IsFlagSet&lt;T&gt;(this T firstOperand, T secondOperand) \n                                                  where T : struct\n        {\n\n            Type enumType = typeof(T);\n\n\n            if (!enumType.IsEnum)\n            {\n                throw new InvalidOperationException("Enum type parameter required");\n            }\n\n\n            Delegate funcImplementorBase = null;\n            m_operations.TryGetValue(enumType, out funcImplementorBase);\n\n            Func&lt;T, T, bool&gt; funcImplementor = funcImplementorBase as Func&lt;T, T, bool&gt;;\n\n            if (funcImplementor == null)\n            {\n                funcImplementor = buildFuncImplementor(secondOperand);\n            }\n\n\n\n            return funcImplementor(firstOperand, secondOperand);\n        }\n\n\n        private static Func&lt;T, T, bool&gt; buildFuncImplementor&lt;T&gt;(T val)\n                                                            where T : struct\n        {\n            var first = Expression.Parameter(val.GetType(), "first");\n            var second = Expression.Parameter(val.GetType(), "second");\n\n            Expression convertSecondExpresion = Expression.Convert(second, typeof(int));\n            var andOperator = Expression.Lambda&lt;Func&lt;T, T, bool&gt;&gt;(Expression.Equal(\n                                                                                                       Expression.And(\n                                                                                                            Expression.Convert(first, typeof(int)),\n                                                                                                             convertSecondExpresion),\n                                                                                                       convertSecondExpresion),\n                                                                                             new[] { first, second });\n            Func&lt;T, T, bool&gt; andOperatorFunc = andOperator.Compile();\n            m_operations[typeof(T)] = andOperatorFunc;\n            return andOperatorFunc;\n        }\n    }\n\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            MyFlags flag = MyFlags.A | MyFlags.B;\n\n            Console.WriteLine(flag.IsFlagSet(MyFlags.A));            \n            Console.WriteLine(EnumExtensions.IsFlagSet(flag, MyFlags.C));\n            Console.ReadLine();\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 593134, 'author': 'Jonathan Parker', 'author_id': 4504, 'author_profile': 'https://Stackoverflow.com/users/4504', 'pm_score': 3, 'selected': False, 'text': "<p>Method groups aren't well known.</p>\n\n<p>Given:</p>\n\n<pre><code>Func&lt;Func&lt;int,int&gt;,int,int&gt; myFunc1 = (i, j) =&gt; i(j);\nFunc&lt;int, int&gt; myFunc2 = i =&gt; i + 2;\n</code></pre>\n\n<p>You can do this:</p>\n\n<pre><code>var x = myFunc1(myFunc2, 1);\n</code></pre>\n\n<p>instead of this:</p>\n\n<pre><code>var x = myFunc1(z =&gt; myFunc2(z), 1);\n</code></pre>\n"}, {'answer_id': 618582, 'author': 'tuinstoel', 'author_id': 43901, 'author_profile': 'https://Stackoverflow.com/users/43901', 'pm_score': 4, 'selected': False, 'text': '<p>You can use generics to check (compile time) if a method argument implements two interfaces:</p>\n\n<pre><code>interface IPropA \n{\n    string PropA { get; set; } \n}\n\ninterface IPropB \n{\n    string PropB { get; set; }\n}\n\nclass TestClass \n{\n    void DoSomething&lt;T&gt;(T t) where T : IPropA, IPropB \n    {\n        MessageBox.Show(t.PropA);\n        MessageBox.Show(t.PropB);\n    }\n}\n</code></pre>\n\n<p>Same with an argument that is inherited from a base class and an interface. </p>\n'}, {'answer_id': 637760, 'author': 'kentaromiura', 'author_id': 27340, 'author_profile': 'https://Stackoverflow.com/users/27340', 'pm_score': 3, 'selected': False, 'text': '<p>Is constructor chain already cited?</p>\n\n<pre><code>namespace constructorChain {\n    using System;\n\n    public class Class1 {\n        public string x;\n        public string y;\n\n        public Class1() {\n            x = "class1";\n            y = "";\n        }\n\n        public Class1(string y)\n            : this() {\n            this.y = y;\n        }\n    }\n\n    public class Class2 : Class1 {\n        public Class2(int y)\n            : base(y.ToString()) {\n\n        }\n    }\n}\n</code></pre>\n\n<p>...</p>\n\n<pre><code>        constructorChain.Class1 c1 = new constructorChain.Class1();\n        constructorChain.Class1 c12 = new constructorChain.Class1("Hello, Constructor!");\n        constructorChain.Class2 c2 = new constructorChain.Class2(10);\n        Console.WriteLine("{0}:{1}", c1.x, c1.y);\n        Console.WriteLine("{0}:{1}", c12.x, c12.y);\n        Console.WriteLine("{0}:{1}", c2.x, c2.y);\n\n        Console.ReadLine();\n</code></pre>\n'}, {'answer_id': 699973, 'author': 'Raghu Dodda', 'author_id': 84940, 'author_profile': 'https://Stackoverflow.com/users/84940', 'pm_score': 1, 'selected': False, 'text': '<p>Not hidden, but pretty neat. I find this a more succinct substitute for a simple if-then-else that just assigns a value based on a condition.</p>\n\n<pre><code>string result = \n              i &lt; 2 ?               //question\n              "less than 2" :       //answer\n              i &lt; 5 ?               //question\n             "less than 5":         //answer   \n              i &lt; 10 ?              //question\n              "less than 10":       //answer\n              "something else";     //default answer \n</code></pre>\n'}, {'answer_id': 707480, 'author': 'DSO', 'author_id': 38087, 'author_profile': 'https://Stackoverflow.com/users/38087', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s one I discovered recently which has been useful:</p>\n\n<pre><code>Microsoft.VisualBasic.Logging.FileLogTraceListener\n</code></pre>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.logging.filelogtracelistener.aspx" rel="nofollow noreferrer">MSDN Link</a></p>\n\n<p>This is a TraceListener implementation which has a lot of features, such as automatic log file roll over, which I previously would use a custom logging framework for.  The nice thing is that it is a core part of .NET and is integrated with the Trace framework, so its easy to pick up and use immediately.</p>\n\n<p>This is "hidden" because its in the Microsoft.VisualBasic assembly... but you can use it from C# as well.</p>\n'}, {'answer_id': 709198, 'author': 'Waleed Eissa', 'author_id': 676066, 'author_profile': 'https://Stackoverflow.com/users/676066', 'pm_score': 3, 'selected': False, 'text': '<p>Working with enums.</p>\n\n<p>Convert a string to an Enum:</p>\n\n<pre><code>enum MyEnum\n{\n    FirstValue,\n    SecondValue,\n    ThirdValue\n}\n\nstring enumValueString = "FirstValue";\nMyEnum val = (MyEnum)Enum.Parse(typeof(MyEnum), enumValueString, true)\n</code></pre>\n\n<ul>\n<li>I use this to load the value of CacheItemPriority in my ASP.NET applications from a settings table in a database so that I can control caching (along with other settings) dynamically without taking the application down.</li>\n</ul>\n\n<p>When comparing variables of type enum, you don\'t have to cast to int:</p>\n\n<pre><code>MyEnum val = MyEnum.SecondValue;\nif (val &lt; MyEnum.ThirdValue)\n{\n    // Do something\n}\n</code></pre>\n'}, {'answer_id': 710507, 'author': 'Gorkem Pacaci', 'author_id': 51749, 'author_profile': 'https://Stackoverflow.com/users/51749', 'pm_score': 3, 'selected': False, 'text': "<p>I quite enjoy implicit generic parameters on functions. For example, if you have:</p>\n\n<pre><code>public void DoStuff&lt;T&gt;(T value);\n</code></pre>\n\n<p>Instead of calling it like this:</p>\n\n<pre><code>DoStuff&lt;int&gt;(5);\n</code></pre>\n\n<p>You can:</p>\n\n<pre><code>DoStuff(5);\n</code></pre>\n\n<p>And it'll work out the generic type from the parameter's type. </p>\n\n<ul>\n<li>This doesn't work if you're calling the method through reflection.</li>\n<li>I remember having some weird problems on Mono.</li>\n</ul>\n"}, {'answer_id': 749846, 'author': 'Ralph Caraveo', 'author_id': 71079, 'author_profile': 'https://Stackoverflow.com/users/71079', 'pm_score': 7, 'selected': False, 'text': "<p>Many people don't realize that they can compare strings using: OrdinalIgnoreCase instead of having to do someString.ToUpper().  This removes the additional string allocation overhead.</p>\n\n<pre><code>if( myString.ToUpper() == theirString.ToUpper() ){ ... }\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>if( myString.Equals( theirString, StringComparison.OrdinalIgnoreCase ) ){ ... }\n</code></pre>\n"}, {'answer_id': 759323, 'author': 'Peter Lillevold', 'author_id': 35245, 'author_profile': 'https://Stackoverflow.com/users/35245', 'pm_score': 4, 'selected': False, 'text': '<p>My favorite attribute: <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx" rel="nofollow noreferrer">InternalsVisibleTo</a></p>\n\n<p>At assembly level you can declare that another assembly can see your internals. For testing purposes this is absolutely wonderful. </p>\n\n<p>Stick this in your AssemblyInfo.cs or equivalent and your test assembly get full access to all the internal stuff that requires testing.</p>\n\n<pre><code>[assembly: InternalsVisibleTo("MyLibrary.Test, PublicKey=0024...5c042cb")]\n</code></pre>\n\n<p>As you can see, the test assembly must have <a href="http://msdn.microsoft.com/en-us/library/xc31ft41.aspx" rel="nofollow noreferrer">a strong name</a> to gain the trust of the assembly under test.</p>\n\n<p>Available in .Net Framework 2.0+, Compact Framework 2.0+ and XNA Framework 1.0+.</p>\n'}, {'answer_id': 781561, 'author': 'Akash Kava', 'author_id': 85597, 'author_profile': 'https://Stackoverflow.com/users/85597', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p><strong>FIXED</strong> / Power of Pointers in C# - This topic is too big, but I will just outline simple things.</p>\n</blockquote>\n\n<p>In C we had facility of loading structure like...</p>\n\n<pre><code>struct cType{\n   char type[4];\n   int  size;\n   char name[50];\n   char email[100];\n}\n\ncType myType;\nfread(file, &amp;mType, sizeof(mType));\n</code></pre>\n\n<p>We can use fixed keyword in "unsafe" method to read byte array aligned structure.</p>\n\n<pre><code>[Layout(LayoutKind.Sequential, Pack=1)]\npublic unsafe class CType{\n    public fixed byte type[4];\n    public int size;\n    public fixed byte name[50];\n    public fixed byte email[100];\n}\n</code></pre>\n\n<p>Method 1 (Reading from regular stream in to byte buffer and mapping byte array to individual bytes of struct)</p>\n\n<pre><code>CType mType = new CType();\nbyte[] buffer = new byte[Marshal.SizeOf(CType)];\nstream.Read(buffer,0,buffer.Length);\n// you can map your buffer back to your struct...\nfixed(CType* sp = &amp;mType)\n{\n    byte* bsp = (byte*) sp;\n    fixed(byte* bp = &amp;buffer)\n    {\n         for(int i=0;i&lt;buffer.Length;i++)\n         {\n             (*bsp) = (*bp);\n             bsp++;bp++;\n         }\n    }\n}\n</code></pre>\n\n<p>Method 2, you can map Win32 User32.dll\'s ReadFile to directly read bytes...</p>\n\n<pre><code>CType mType = new CType();\nfixed(CType* p = &amp;mType)\n{\n    User32.ReadFile(fileHandle, (byte*) p, Marshal.SizeOf(mType),0);\n}\n</code></pre>\n'}, {'answer_id': 791096, 'author': 'Elroy', 'author_id': 56097, 'author_profile': 'https://Stackoverflow.com/users/56097', 'pm_score': 3, 'selected': False, 'text': '<p>The usage of the default keyword in generic code to return the default value for a type.</p>\n\n<pre><code>public class GenericList&lt;T&gt;\n{\n    private class Node\n    {\n        //...\n\n        public Node Next;\n        public T Data;\n    }\n\n    private Node head;\n\n    //...\n\n    public T GetNext()\n    {\n        T temp = default(T);\n\n        Node current = head;\n        if (current != null)\n        {\n            temp = current.Data;\n            current = current.Next;\n        }\n        return temp;\n    }\n}\n</code></pre>\n\n<p><a href="https://stackoverflow.com/questions/367378/returning-a-default-value-c">Another example here</a></p>\n'}, {'answer_id': 794343, 'author': 'Dries Van Hansewijck', 'author_id': 95981, 'author_profile': 'https://Stackoverflow.com/users/95981', 'pm_score': 2, 'selected': False, 'text': '<p>The InternalsVisibleToAttribute specifies that types that are ordinarily visible only within the current assembly are visible to another assembly. <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx" rel="nofollow noreferrer" title="InternalsVisibleToAttribute class">Article on msdn</a></p>\n'}, {'answer_id': 821718, 'author': 'rein', 'author_id': 100142, 'author_profile': 'https://Stackoverflow.com/users/100142', 'pm_score': 3, 'selected': False, 'text': '<p>Instead of doing something cheesy like this:</p>\n\n<pre><code>Console.WriteLine("{0} item(s) found.", count);\n</code></pre>\n\n<p>I use the following inline trick:</p>\n\n<pre><code>Console.WriteLine("{0} item{1} found.", count, count==1 ? "" : "s");\n</code></pre>\n\n<p>This will display "item" when there\'s one item or "items" when there are more (or less) than 1. Not much effort for a little bit of professionalism.</p>\n'}, {'answer_id': 840445, 'author': 'nsantorello', 'author_id': 94824, 'author_profile': 'https://Stackoverflow.com/users/94824', 'pm_score': 3, 'selected': False, 'text': '<p>One thing not many people know about are some of the C#-introduced preprocessor directives.  You can use <code>#error This is an error.</code> to generate a compiler error and <code>#warning This is a warning.</code></p>\n\n<p>I usually use these when I\'m developing with a top-down approach as a "todo" list.  I\'ll <code>#error Implement this function</code>, or <code>#warning Eventually implement this corner case</code> as a reminder.</p>\n'}, {'answer_id': 840998, 'author': 'Drew Hoskins', 'author_id': 97235, 'author_profile': 'https://Stackoverflow.com/users/97235', 'pm_score': 2, 'selected': False, 'text': '<p>In dealing with interop between C++ and C#, many people don\'t realize that C++/CLI is a great option.</p>\n\n<p>Say you have a C++ DLL and a C# DLL which depends on the C++ DLL.  Often, the easiest technique is to compile some (or all) modules of the C++ DLL with the /clr switch. To have the C# call the C++ DLL is to write managed C++ wrapper classes in the C++ DLL.  The C++/CLI classes can call the native C++ code much more seamlessly than C#, because the C++ compiler will automatically generate P/invokes for you, has a library specifically for interop, plus language features for interop like <a href="http://msdn.microsoft.com/en-us/library/1dz8byfh(VS.80).aspx" rel="nofollow noreferrer">pin_ptr</a>.  And it allows managed and native code to coexist within the same binary.</p>\n\n<p>On the C# side, you just call into the DLL as you would any other .NET binary.</p>\n'}, {'answer_id': 841140, 'author': 'Jeff Yates', 'author_id': 23234, 'author_profile': 'https://Stackoverflow.com/users/23234', 'pm_score': 3, 'selected': False, 'text': '<p>I am so so late to this question, but I wanted to add a few that I don\'t think have been covered. These aren\'t C#-specific, but I think they\'re worthy of mention for any C# developer.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.ambientvalueattribute.aspx" rel="nofollow noreferrer"><h3>AmbientValueAttribute</h3></a>\nThis is similar to <code>DefaultValueAttribute</code>, but instead of providing the value that a property defaults to, it provides the value that a property uses to decide whether to request its value from somewhere else. For example, for many controls in WinForms, their <code>ForeColor</code> and <code>BackColor</code> properties have an <code>AmbientValue</code> of <code>Color.Empty</code> so that they know to get their colors from their parent control.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings(VS.95).aspx" rel="nofollow noreferrer"><h3>IsolatedStorageSettings</h3></a>\nThis is a Silverlight one. The framework handily includes this sealed class for providing settings persistence at both the per-application and per-site level.</p>\n\n<h3>Flag interaction with extension methods</h3>\n\n<p>Using extension methods, flag enumeration use can be a lot more readable.</p>\n\n<pre><code>    public static bool Contains(\n          this MyEnumType enumValue,\n          MyEnumType flagValue)\n    {\n        return ((enumValue &amp; flagValue) == flagValue);\n    }\n\n    public static bool ContainsAny(\n          this MyEnumType enumValue,\n          MyEnumType flagValue)\n    {\n        return ((enumValue &amp; flagValue) &gt; 0);\n    }\n</code></pre>\n\n<p>This makes checks for flag values nice and easy to read and write. Of course, it would be nicer if we could use generics and enforce T to be an enum, but that isn\'t allowed. Perhaps <code>dynamic</code> will make this easier.</p>\n'}, {'answer_id': 862323, 'author': 'Ash', 'author_id': 5023, 'author_profile': 'https://Stackoverflow.com/users/5023', 'pm_score': 3, 'selected': False, 'text': '<p>The built-in (2.0) MethodInvoker delegate is useful when you want to Invoke/BeginInvoke inline code.  This avoids needing to create an actual delegate and separate method.</p>\n\n<pre><code>    void FileMessageEvent(object sender, MessageEventArgs e)\n    {\n\n        if (this.InvokeRequired == true)\n        {\n            this.BeginInvoke((MethodInvoker)delegate { \n                     lblMessage.Text=e.Message; \n                     Application.DoEvents(); \n                 }\n            ); \n\n        }\n    }\n</code></pre>\n\n<p>Resolves the error:  "Cannot convert anonymous method to type \'System.Delegate\' because it is not a delegate type".</p>\n'}, {'answer_id': 874167, 'author': 'Josef Pfleger', 'author_id': 98401, 'author_profile': 'https://Stackoverflow.com/users/98401', 'pm_score': 3, 'selected': False, 'text': '<p>I find it incredible what type of trouble the compiler goes through to sugar code the use of <strong>Outer Variables</strong>:</p>\n\n<pre><code>string output = "helo world!";\nAction action = () =&gt; Console.WriteLine(output);\noutput = "hello!";\naction();\n</code></pre>\n\n<p>This actually prints <code>hello!</code>. Why? Because the compiler creates a nested class for the delegate, with public fields for all <em>outer variables</em> and inserts setting-code before every single call to the delegate :) Here is above code \'reflectored\':</p>\n\n<pre><code>Action action;\n&lt;&gt;c__DisplayClass1 CS$&lt;&gt;8__locals2;\nCS$&lt;&gt;8__locals2 = new &lt;&gt;c__DisplayClass1();\nCS$&lt;&gt;8__locals2.output = "helo world!";\naction = new Action(CS$&lt;&gt;8__locals2.&lt;Main&gt;b__0);\nCS$&lt;&gt;8__locals2.output = "hello!";\naction();\n</code></pre>\n\n<p>Pretty cool I think.</p>\n'}, {'answer_id': 882100, 'author': 'Shalom Craimer', 'author_id': 54491, 'author_profile': 'https://Stackoverflow.com/users/54491', 'pm_score': 3, 'selected': False, 'text': "<p>I couldn't figure out what use some of the functions in the <code>Convert</code> class had (such as Convert.ToDouble(int), Convert.ToInt(double)) until I combined them with <code>Array.ConvertAll</code>:</p>\n\n<pre><code>int[] someArrayYouHaveAsInt;\ndouble[] copyOfArrayAsDouble = Array.ConvertAll&lt;int, double&gt;(\n                                someArrayYouHaveAsInt,\n                                new Converter&lt;int,double&gt;(Convert.ToDouble));\n</code></pre>\n\n<p>Which avoids the resource allocation issues that arise from defining an inline delegate/closure (and slightly more readable):</p>\n\n<pre><code>int[] someArrayYouHaveAsInt;\ndouble[] copyOfArrayAsDouble = Array.ConvertAll&lt;int, double&gt;(\n                                someArrayYouHaveAsInt,\n                                new Converter&lt;int,double&gt;(\n                                  delegate(int i) { return (double)i; }\n                                ));\n</code></pre>\n"}, {'answer_id': 883586, 'author': 'JoshL', 'author_id': 20625, 'author_profile': 'https://Stackoverflow.com/users/20625', 'pm_score': 3, 'selected': False, 'text': '<p>Array initialization without specifying the array element type:</p>\n\n<pre><code>var pets = new[] { "Cat", "Dog", "Bird" };\n</code></pre>\n'}, {'answer_id': 899593, 'author': 'Oorang', 'author_id': 102270, 'author_profile': 'https://Stackoverflow.com/users/102270', 'pm_score': 2, 'selected': False, 'text': "<p>Well... <strong><em>Don't use it</em></strong>, but a lot of people don't know C# supports the evil goto:)</p>\n\n<pre><code>static void Example()\n{\n    int i = 0;\ntop:\n    Console.WriteLine(i.ToString());\n    if (i == 0)\n    {\n        i++;\n        goto top;\n    }\n}\n</code></pre>\n"}, {'answer_id': 912833, 'author': 'sourcenouveau', 'author_id': 111327, 'author_profile': 'https://Stackoverflow.com/users/111327', 'pm_score': 3, 'selected': False, 'text': '<p>Having just learned the meaning of invariance, covariance and contravariance, I discovered the <a href="http://msdn.microsoft.com/en-us/library/dd469484(VS.100).aspx" rel="nofollow noreferrer">in</a> and <a href="http://msdn.microsoft.com/en-us/library/dd469487(VS.100).aspx" rel="nofollow noreferrer">out</a> generic modifiers that will be included in .NET 4.0. They seem obscure enough that most programmers would not know about them.</p>\n\n<p>There\'s an <a href="http://visualstudiomagazine.com/articles/2009/05/01/generic-covariance-and-contravariance-in-c-40.aspx" rel="nofollow noreferrer">article</a> at Visual Studio Magazine which discusses these keywords and how they will be used.</p>\n'}, {'answer_id': 938302, 'author': 'Dave Van den Eynde', 'author_id': 455874, 'author_profile': 'https://Stackoverflow.com/users/455874', 'pm_score': 4, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/b3787ac0.aspx" rel="nofollow noreferrer">Atrribute Targets</a></p>\n\n<p>Everyone has seen one. Basically, when you see this:</p>\n\n<pre><code>[assembly: ComVisible(false)]\n</code></pre>\n\n<p>The "assembly:" portion of that attribute is the target. In this case, the attribute is applied to the assembly, but there are others:</p>\n\n<pre><code>[return: SomeAttr]\nint Method3() { return 0; } \n</code></pre>\n\n<p>In this sample the attribute is applied to the return value. </p>\n'}, {'answer_id': 945247, 'author': 'Showtime', 'author_id': 114893, 'author_profile': 'https://Stackoverflow.com/users/114893', 'pm_score': 1, 'selected': False, 'text': '<p>If you want to prevent the garbage collector from running the finalizer of an object, just use <code>GC.SuppressFinalize(object);</code>. In a similar vein, <code>GC.KeepAlive(object);</code> will prevent the garbage collector from collecting that object by referencing it. Not very commonly used, at least in my experience, but nice to know just in  case.</p>\n'}, {'answer_id': 945300, 'author': 'Lloyd Powell', 'author_id': 67258, 'author_profile': 'https://Stackoverflow.com/users/67258', 'pm_score': 3, 'selected': False, 'text': '<p>Properties to display when viewing components Properties in design view:</p>\n\n<pre><code>private double _Zoom = 1;\n\n[Category("View")]\n[Description("The Current Zoom Level")]\npublic double Zoom\n{\nget { return _Zoom;}\nset { _Zoom = value;}\n}\n</code></pre>\n\n<p>Makes things a lot easier for other users of your component libraries.</p>\n'}, {'answer_id': 945458, 'author': 'Jeffrey Hines', 'author_id': 107972, 'author_profile': 'https://Stackoverflow.com/users/107972', 'pm_score': 2, 'selected': False, 'text': '<p>Relection is so powerfull when used carefully. I used it in an e-mail templating system. The template manager would be passed an object and the html templates would have embedded fields that referred to Properties that could be retrieved off the passed object using reflection. Worked out very nicely.</p>\n'}, {'answer_id': 949309, 'author': 'RCIX', 'author_id': 117069, 'author_profile': 'https://Stackoverflow.com/users/117069', 'pm_score': 2, 'selected': False, 'text': "<p>Definitely the Func&lt;> types when used with statement lambdas in .NET 3.5. These allow customizable functions, and can be a great aid in offering user customizable objects without subclassing them or resorting to some limited system like keeping track of a variable that lists what button or key the user wants to monitor. Also, they can be called just like regular methods and can be assigned like variables. The only downside that I can think of is that you're limited to 5 arguments! Although by that point you might want to consider a different solution...\nEdit: Providing some examples.</p>\n\n<pre><code>...\npublic Func&lt;InputHelper, float&gt; _horizontalCameraMovement = (InputHelper input) =&gt; \n{\n    return (input.LeftStickPosition.X * _moveRate) * _zoom;\n}\npublic Func&lt;InputHelper, float&gt; _verticalCameraMovement = (InputHelper input) =&gt; \n{\n    return (-input.LeftStickPosition.Y * _moveRate) * _zoom;\n}\n...\npublic void Update(InputHelper input)\n{\n    ...\n    position += new Vector2(_horizontalCameraMovement(input), _verticalCameraMovement(input));\n    ...\n}\n</code></pre>\n\n<p>In this example, you can write a function that does arbitrary calculation and returns a float that will determine the amount that the camera moves by. Not the best code but it gets the point across.</p>\n\n<pre><code>private int foo;\npublic int FooProperty {\n    get\n    {\n        if (_onFooGotten() == true)\n            return _foo;\n    }\n    set\n    {\n        if (onFooSet() == true)\n            _foo = value;\n    }\n}\n...\npublic Func&lt;bool&gt; _onFooGotten = () =&gt; \n{\n    //do whatever...\n    return true;\n}\npublic Func&lt;bool&gt; _onFooSet = () =&gt;\n{\n    //do whatever...\n    return true;\n}\n</code></pre>\n\n<p>This isn't the best example (as I haven't really explored this use yet) but it shows an example of using a lambda function for a quick event raiser without the hassle of delegates.\nEdit: thought of another one. Nullables! The closest thing C# has to optional parameters.</p>\n"}, {'answer_id': 957443, 'author': 'Andrew Lavers', 'author_id': 77501, 'author_profile': 'https://Stackoverflow.com/users/77501', 'pm_score': 4, 'selected': False, 'text': '<p>FlagsAttribute, a small but <a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx" rel="nofollow noreferrer">nice feature</a> when using enum to make a bitmasks:</p>\n\n<pre><code>[Flags]\npublic enum ConfigOptions\n{\n    None    = 0,\n    A       = 1 &lt;&lt; 0,\n    B       = 1 &lt;&lt; 1,\n    Both    = A | B\n}\n\nConsole.WriteLine( ConfigOptions.A.ToString() );\nConsole.WriteLine( ConfigOptions.Both.ToString() );\n// Will print:\n// A\n// A, B\n</code></pre>\n'}, {'answer_id': 958103, 'author': 'Kevin Doyon', 'author_id': 78804, 'author_profile': 'https://Stackoverflow.com/users/78804', 'pm_score': 2, 'selected': False, 'text': '<p>If you have the search textbox in your Visual Studio toolbar, you can type ">of Program.cs" to open the file Program.cs</p>\n'}, {'answer_id': 961401, 'author': 'Tolgahan Albayrak', 'author_id': 104468, 'author_profile': 'https://Stackoverflow.com/users/104468', 'pm_score': 3, 'selected': False, 'text': '<p>The data type can be defined for an enumeration:</p>\n\n<pre><code>enum EnumName : [byte, char, int16, int32, int64, uint16, uint32, uint64]\n{\n    A = 1,\n    B = 2\n}\n</code></pre>\n'}, {'answer_id': 993118, 'author': 'zebrabox', 'author_id': 122755, 'author_profile': 'https://Stackoverflow.com/users/122755', 'pm_score': 2, 'selected': False, 'text': '<p>A few from me - make of them what you will.</p>\n\n<p>The attribute:</p>\n\n<pre><code>[assembly::InternalsVisibleTo("SomeAssembly")]\n</code></pre>\n\n<p>Allows you to expose out the internal methods/properties or data from your assembly to another assembly called \'SomeAssembly\'. All protected/private stuff remains hidden.</p>\n\n<hr>\n\n<p>Static constructors ( otherwise called \'Type Constructor\' )</p>\n\n<pre><code>public MyClass\n{\n  public static MyClass()\n  {\n     // type init goes here\n  }\n  ......\n}  \n</code></pre>\n\n<hr>\n\n<p>The keyword <code>internal</code>. So useful in so many ways.</p>\n'}, {'answer_id': 993271, 'author': 'ShuggyCoUk', 'author_id': 12748, 'author_profile': 'https://Stackoverflow.com/users/12748', 'pm_score': 3, 'selected': False, 'text': '<h2>Advanced Debugging</h2>\n<h3>Display</h3>\n<p>The already mentioned attributes DebuggerDisplay and DebuggerBrowsable control the visibility of elements and the textual value displayed. Simply overriding ToString() will cause the debugger to use the output of that method.</p>\n<p>If you want more complex output you can use/create a <a href="http://msdn.microsoft.com/en-us/library/zayyhzts.aspx" rel="nofollow noreferrer">Debugger Visualizer</a>, several examples\nare available <a href="http://www.dotnetpowered.com/DebuggerVisualizers.aspx" rel="nofollow noreferrer">here</a>.</p>\n<h3>Son Of Strike</h3>\n<p>Microsoft provide a debugger extension known as <a href="http://msdn.microsoft.com/en-us/library/bb190764(vs.80).aspx" rel="nofollow noreferrer">SOS</a>. This is an extremely powerful (though often confusing) extension which is an excellent way to diagnose \'leaks\', more accurately unwanted references to objects no longer required.</p>\n<h3>Symbol Server for framework source</h3>\n<p>Following these <a href="http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx" rel="nofollow noreferrer">instructions</a> will allow you to step through the source of some parts of the framework.</p>\n<h3>Changes in 2010</h3>\n<p>Several enhancements and new features exist in Visual Studio 2010:</p>\n<ul>\n<li><a href="http://www.danielmoth.com/Blog/2009/05/parallel-tasks-new-visual-studio-2010.html" rel="nofollow noreferrer">Debugging Parallel Tasks</a></li>\n<li><a href="http://www.danielmoth.com/Blog/2009/05/parallel-stacks-another-new-vs2010.html" rel="nofollow noreferrer">Parallel Stacks</a> allow viewing multiple threads call stacks at the same time.</li>\n<li><a href="http://channel9.msdn.com/posts/VisualStudio/Historical-Debugger-and-Test-Impact-Analysis-in-Visual-Studio-Team-System-2010/" rel="nofollow noreferrer">Historical Debugging</a> lets you see events and non-local variables back in time (so long as you enable the collection in advance). Potentially a significant change to how you debug things.</li>\n</ul>\n'}, {'answer_id': 1002816, 'author': 'JoshL', 'author_id': 20625, 'author_profile': 'https://Stackoverflow.com/users/20625', 'pm_score': 6, 'selected': False, 'text': '<p><strong>Use "throw;" instead of "throw ex;" to preserve stack trace</strong></p>\n\n<p>If re-throwing an exception without adding additional information, use "throw" instead of "throw ex". An empty "throw" statement in a catch block will emit specific IL that re-throws the exception while preserving the original stack trace. "throw ex" loses the stack trace to the original source of the exception.</p>\n'}, {'answer_id': 1003232, 'author': 'epitka', 'author_id': 103682, 'author_profile': 'https://Stackoverflow.com/users/103682', 'pm_score': 2, 'selected': False, 'text': '<p>Ability to create instance of the type based on the generic parameter like this</p>\n\n<p>new T();</p>\n'}, {'answer_id': 1010679, 'author': 'statenjason', 'author_id': 88340, 'author_profile': 'https://Stackoverflow.com/users/88340', 'pm_score': 3, 'selected': False, 'text': '<p>The Yield keyword is often overlooked when it has a lot of power. I blogged about it awhile ago and discussed benefits (differed processing) and happens under the hood of yield to help give a stronger understanding.</p>\n\n<p><a href="http://jxs.me/2010/05/14/using-yield-in-c/" rel="nofollow noreferrer">Using Yield in C#</a></p>\n'}, {'answer_id': 1016037, 'author': 'SLaks', 'author_id': 34397, 'author_profile': 'https://Stackoverflow.com/users/34397', 'pm_score': 3, 'selected': False, 'text': '<p>You can create delegates from extension methods as if they were regular methods, currying the <code>this</code> parameter.  For example, </p>\n\n<pre><code>static class FunnyExtension {\n    public static string Double(this string str) { return str + str; }\n    public static int Double(this int num) { return num + num; }\n}\n\n\nFunc&lt;string&gt; aaMaker = "a".Double;\nFunc&lt;string, string&gt; doubler = FunnyExtension.Double;\n\nConsole.WriteLine(aaMaker());       //Prints "aa"\nConsole.WriteLine(doubler("b"));    //Prints "bb"\n</code></pre>\n\n<p>Note that this won\'t work on extension methods that extend \na value type; see <a href="https://stackoverflow.com/questions/1016033/extension-methods-defined-on-value-types-cannot-be-used-to-create-delegates-why">this question</a>.</p>\n'}, {'answer_id': 1017882, 'author': 'Titian Cernicova-Dragomir', 'author_id': 125734, 'author_profile': 'https://Stackoverflow.com/users/125734', 'pm_score': 3, 'selected': False, 'text': '<p>Not sure if this one got mentioned yet but the ThreadStatic attribute is a realy useful one. This makes a static field static just for the current thread.</p>\n\n<pre><code>[ThreadStatic]\nprivate static int _ThreadStaticInteger;\n</code></pre>\n\n<p>You should not include an initializer because it only get executed once for the entire application, you\'re better off making the field nullable and checking if the value is null before you use it.</p>\n\n<p>And one more thing for ASP.NET applications threads are reused so if you modify the value it could end up being used for another page request.</p>\n\n<p>Still I have found this useful on several occasions. For example in creating a custom transaction class that:</p>\n\n<pre><code>using (DbTransaction tran = new DbTransaction())\n{\n    DoQuery("...");\n    DoQuery("...");    \n}\n</code></pre>\n\n<p>The DbTransaction constructor sets a ThreadStatic field to its self and resets it to null in the dispose method. DoQuery checks the static field and if != null uses the current transaction if not it defaults to something else. We avoid having to pass the transaction to each method plus it makes it easy to wrap other methods that were not originaly meant to be used with transaction inside a transaction ...</p>\n\n<p>Just one use :)</p>\n'}, {'answer_id': 1025614, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<pre><code>HttpContext.Current.Server.Execute \n</code></pre>\n\n<p>is great for rendering HTML to strings for AJAX callbacks.  You can use this with a component instead of piecing together HTML string snippets.  I was able to cut page bloat down a couple of hundred KB with virtually no mess.  I used it like this:</p>\n\n<pre><code>Page pageHolder = new Page();\nUserControl viewControl = (UserControl)pageHolder.LoadControl(@"MyComponent.ascx");\npageHolder.Controls.Add(viewControl);\nStringWriter output = new StringWriter();\nHttpContext.Current.Server.Execute(pageHolder, output, false);\nreturn output.ToString();\n</code></pre>\n'}, {'answer_id': 1026941, 'author': 'Paul Ruane', 'author_id': 83264, 'author_profile': 'https://Stackoverflow.com/users/83264', 'pm_score': 2, 'selected': False, 'text': '<p>Marketing events as non-serializable:</p>\n\n<pre><code>[field:NonSerializable]\npublic event SomeDelegate SomeEvent;\n</code></pre>\n'}, {'answer_id': 1049977, 'author': 'Mike', 'author_id': 127831, 'author_profile': 'https://Stackoverflow.com/users/127831', 'pm_score': 4, 'selected': False, 'text': '<p>You can add and remove delegates with less typing.</p>\n\n<p>Usual way:</p>\n\n<pre><code>handler += new EventHandler(func);\n</code></pre>\n\n<p>Less typing way:</p>\n\n<pre><code>handler += func;\n</code></pre>\n'}, {'answer_id': 1062170, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Generic constraints:</p>\n\n<pre><code> //Constructor constraint, T has a default empty constructor\nclass Node&lt;K,T&gt; where T : new() \n{\n}\n\n//Reference\\Value Type constraints\n//T is a struct\npublic class MyClass&lt;T&gt; where T : struct \n\n{...}\n\n//T is a reference type\npublic class MyClass&lt;T&gt; where T : class \n\n{...}\n\npublic class MyClass&lt;T&gt; where T : SomeBaseClass, ISomeInterface \n\n{...}\n</code></pre>\n'}, {'answer_id': 1062556, 'author': 'Mark Seemann', 'author_id': 126014, 'author_profile': 'https://Stackoverflow.com/users/126014', 'pm_score': 3, 'selected': False, 'text': '<p>The <code>Or</code> assignment operator is quite nice. You can write this:</p>\n\n<pre><code>x |= y\n</code></pre>\n\n<p>instead of this:</p>\n\n<pre><code>x = x | y\n</code></pre>\n\n<p>This is often practical if you have to a variable or property (<code>x</code> in the example) that starts out as <code>false</code> but you want to change it to the value of some other boolean variable/property <em>only when</em> that other value is <code>true</code>.</p>\n'}, {'answer_id': 1071983, 'author': 'Wim Coenen', 'author_id': 52626, 'author_profile': 'https://Stackoverflow.com/users/52626', 'pm_score': 4, 'selected': False, 'text': '<p>Extension methods can be called on <code>null</code>; this will not cause a <code>NullReferenceException</code> to be thrown.</p>\n\n<p>Example application: you can define an alternative for <code>ToString()</code> called <code>ToStringOrEmpty()</code> which will return the empty string when called on <code>null</code>.</p>\n'}, {'answer_id': 1114418, 'author': 'Yvo', 'author_id': 136819, 'author_profile': 'https://Stackoverflow.com/users/136819', 'pm_score': 5, 'selected': False, 'text': '<p>I\'ve read through all seven pages, and I\'m missing these:</p>\n\n<p><strong>String.Join</strong></p>\n\n<p>I\'ve seen a lot of for-loops to convert a list of items to a string with separators. It\'s always a pain to make sure you doin\'t start with a separator and don\'t end with a separator. A built-in method makes this easier:</p>\n\n<pre><code>String.Join(",", new String[] { "a", "b", "c"});\n</code></pre>\n\n<p><strong>TODO in comment</strong></p>\n\n<p>Not really a C# feature, more of a Visual Studio feature. When you start your comment with TODO, it\'s added to your Visual Studio Task List (View -> Task List. Comments)</p>\n\n<pre><code>// TODO: Implement this!\nthrow new NotImplementedException();\n</code></pre>\n\n<p><strong>Extension methods meets Generics</strong></p>\n\n<p>You can combine extension methods with Generics, when you think of the tip earlier in this topic, you can add extensions to specific interfaces</p>\n\n<pre><code>public static void Process&lt;T&gt;(this T item) where T:ITest,ITest2 {}\n</code></pre>\n\n<p><strong>Enumerable.Range</strong></p>\n\n<p>Just want a list of integers?</p>\n\n<pre><code>Enumerable.Range(0, 15)\n</code></pre>\n\n<p>I\'ll try to think of some more...</p>\n'}, {'answer_id': 1118859, 'author': 'softveda', 'author_id': 11711, 'author_profile': 'https://Stackoverflow.com/users/11711', 'pm_score': 3, 'selected': False, 'text': '<p>Pointers in C#. </p>\n\n<p>They can be used to do in-place string manipulation. This is an unsafe feature so the unsafe keyword is used to mark the region of unsafe code. Also note how the fixed keyword is used to indicate that the memory pointed to is pinned and cannot be moved by the GC. This is essential a pointers point to memory addresses and the GC can move the memory to different address otherwise resulting in an invalid pointer.</p>\n\n<pre><code>    string str = "some string";\n    Console.WriteLine(str);\n    unsafe\n    {\n        fixed(char *s = str)\n        {\n            char *c = s;\n            while(*c != \'\\0\')\n            {\n                *c = Char.ToUpper(*c++);                    \n            }\n        }\n    }\n    Console.WriteLine(str);\n</code></pre>\n\n<p>I wouldn\'t ever do it but just for the sake of this question to demonstrate this feature.</p>\n'}, {'answer_id': 1135505, 'author': 'David.Chu.ca', 'author_id': 62776, 'author_profile': 'https://Stackoverflow.com/users/62776', 'pm_score': 3, 'selected': False, 'text': '<p>I like to use the <em>using</em> directive to rename some classes for easy reading like this:</p>\n\n<pre><code>// defines a descriptive name for a complexed data type\nusing MyDomainClassList = System.Collections.Generic.List&lt;\n  MyProjectNameSpace.MyDomainClass&gt;;\n\n....\n\n\nMyDomainClassList myList = new MyDomainClassList();\n/* instead of \nList&lt;MyDomainClass&gt; myList = new List&lt;MyDomainClass&gt;();\n*/\n</code></pre>\n\n<p>This is also very handy for code maintenance. If you need to change the class name, there is only one place you need to change. Another example:</p>\n\n<pre><code>using FloatValue  = float; // you only need to change it once to decimal, double...\n\n....\nFloatValue val1;\n...\n</code></pre>\n'}, {'answer_id': 1143637, 'author': 'RandomNickName42', 'author_id': 67819, 'author_profile': 'https://Stackoverflow.com/users/67819', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://code.msdn.microsoft.com/ExceptionFilterInjct" rel="nofollow noreferrer">Exception Filters</a>. So "hidden" you <em>can\'t</em> even use them (at least from C#) without a post-compilation patch ;) </p>\n'}, {'answer_id': 1161934, 'author': 'Dan Diplo', 'author_id': 140392, 'author_profile': 'https://Stackoverflow.com/users/140392', 'pm_score': 2, 'selected': False, 'text': '<p>How about <a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx" rel="nofollow noreferrer">Expression Trees</a>? They are the heart of LINQ and allow for defered execution:</p>\n\n<p>Taken from <a href="http://www.davidhayden.com/blog/dave/archive/2006/12/18/ExpressionTrees.aspx" rel="nofollow noreferrer">David Hayden\'s blog</a>:</p>\n\n<p>In C# 3.0, you can define a delegate as follows using a lambda expression:</p>\n\n<pre><code>Func&lt;int,int&gt; f = x =&gt; x + 1;\n</code></pre>\n\n<p>This delegate is compiled into executable code in your application and can be called as such:</p>\n\n<pre><code>var three = f(2); // 2 + 1\n</code></pre>\n\n<p>The code works as you would expect. Nothing fancy here.</p>\n\n<p><strong>Expression Trees</strong></p>\n\n<p>When you define the delegate as an Expression Tree by using System.Query.Expression:</p>\n\n<pre><code>Expression&lt;Func&lt;int,int&gt;&gt; expression = x =&gt; x + 1;\n</code></pre>\n\n<p>The delegate is no longer compiled into executable code, but compiled as data that can be converted and compiled into the original delegate.</p>\n\n<p>To actually use the delegate represented as an Expression Tree in your application, you would have to compile and invoke it in your application:</p>\n\n<pre><code>var originalDelegate = expression.Compile();\n\nvar three = originalDelegate.Invoke(2);\n</code></pre>\n'}, {'answer_id': 1162648, 'author': 'Martin Konicek', 'author_id': 90998, 'author_profile': 'https://Stackoverflow.com/users/90998', 'pm_score': 3, 'selected': False, 'text': '<pre><code>[field: NonSerialized]\npublic event EventHandler Event;\n</code></pre>\n\n<p>This way, the event listener is not serialized.</p>\n\n<p>Just [NonSerialized] does not work, because NonSerializedAttribute can only be applied to fields.</p>\n'}, {'answer_id': 1163889, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>I especially like the nullable DateTime. So if you have some cases where a Date is given and other cases where no Date is given I think this is best to use and IMHO easier to understand as using <code>DateTime.MinValue</code> or anything else...</p>\n\n<pre><code>DateTime? myDate = null;\n\nif (myDate.HasValue)\n{\n    //doSomething\n}\nelse\n{\n    //soSomethingElse\n}\n</code></pre>\n'}, {'answer_id': 1173935, 'author': 'Brad', 'author_id': 70130, 'author_profile': 'https://Stackoverflow.com/users/70130', 'pm_score': 2, 'selected': False, 'text': '<p>If you are trying to create a comma delimited string from a list of items:</p>\n\n<pre><code>string[] itemList = { "Example 1", "Example 2", "Example 3" };\nCommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();\ncommaStr.AddRange(itemList);\n//outputs Example 1,Example 2,Example 3\n</code></pre>\n\n<p>Look <a href="http://blog.crowe.co.nz/archive/2007/08/25/c---How-to-create-a-comma-seperated-string-from.aspx" rel="nofollow noreferrer">here</a> for another example.</p>\n'}, {'answer_id': 1185988, 'author': 'Paul van Brenk', 'author_id': 1837197, 'author_profile': 'https://Stackoverflow.com/users/1837197', 'pm_score': 3, 'selected': False, 'text': '<p>Zero parameter Lambdas</p>\n\n<pre><code>()=&gt;Console.ReadLine()\n</code></pre>\n'}, {'answer_id': 1204390, 'author': 'ccook', 'author_id': 51275, 'author_profile': 'https://Stackoverflow.com/users/51275', 'pm_score': 3, 'selected': False, 'text': "<p>I didn't see this:</p>\n\n<pre><code>for (;;);\n</code></pre>\n\n<p>The same as</p>\n\n<pre><code>while (true) ;\n</code></pre>\n"}, {'answer_id': 1204441, 'author': 'Brian Surowiec', 'author_id': 39605, 'author_profile': 'https://Stackoverflow.com/users/39605', 'pm_score': 4, 'selected': False, 'text': '<p>I\'m becoming a big fan of extension methods since they can add much wanted functionality to existing code or code you can\'t edit. One of my favorites I add in to everything I do now is for string.IsNullOrEmpty()</p>\n\n<pre><code>public static class Strings\n{\n    public static bool IsNullOrEmpty(this string value)\n    {\n        return string.IsNullOrEmpty(value);\n    }\n}\n</code></pre>\n\n<p>This lets you shorten your code a bit like this</p>\n\n<pre><code>var input = Console.ReadLine();\nif (input.IsNullOrEmpty())\n{\n    Console.WriteLine("try again");\n}\n</code></pre>\n'}, {'answer_id': 1231428, 'author': 'Christian Hubmann', 'author_id': 62910, 'author_profile': 'https://Stackoverflow.com/users/62910', 'pm_score': 6, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SectionSeparator" rel="noreferrer">Conditional string.Format</a>:</p>\n\n<p>Applies different formatting to a number depending on whether the number is positive, negative, or zero.</p>\n\n<pre><code>string s = string.Format("{0:positive;negative;zero}", i);\n</code></pre>\n\n<p>e.g.</p>\n\n<pre><code>string format = "000;-#;(0)";\n\nstring pos = 1.ToString(format);     // 001\nstring neg = (-1).ToString(format);  // -1\nstring zer = 0.ToString(format);     // (0)\n</code></pre>\n'}, {'answer_id': 1234502, 'author': 'John Leidegren', 'author_id': 58961, 'author_profile': 'https://Stackoverflow.com/users/58961', 'pm_score': 2, 'selected': False, 'text': '<p>A lot of this is explained already, in <a href="http://www.ecma-international.org/publications/standards/Ecma-334.htm" rel="nofollow noreferrer">the standard</a>. It\'s a good read for any beginner as well as expert, it\'s a lot to read, but it\'s the official standard, and it\'s filled with juicy details.</p>\n\n<p>Once you fully understand C#, it\'s time to take this further to understand the fundamentals of the <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm" rel="nofollow noreferrer">Common Language Infrastructure</a>. The architecture and underpinnings of C#.</p>\n\n<p>I\'ve met a variety of programmers that don\'t know the difference between an object and a ValueType except the adherent limitations thereof. </p>\n\n<p>Familiarize yourself with these two documents and you\'ll never become that person.</p>\n'}, {'answer_id': 1234603, 'author': 'Ray', 'author_id': 149650, 'author_profile': 'https://Stackoverflow.com/users/149650', 'pm_score': 1, 'selected': False, 'text': '<p>When you need to (a)synchronously communicate between objects about occurance of an event there is special purpose interface called <strong>ISynchronizeInvoke</strong>.</p>\n\n<p>Quoting MSDN article (<a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.isynchronizeinvoke.aspx" rel="nofollow noreferrer">link</a>): </p>\n\n<blockquote>\n  <p>Objects that implement this interface can receive notification that an event has occurred, and they can respond to queries about the event. In this way, clients can ensure that one request has been processed before they submit a subsequent request that depends on completion of the first.</p>\n</blockquote>\n\n<p>Here is a generic wrapper:</p>\n\n<pre><code>protected void OnEvent&lt;T&gt;(EventHandler&lt;T&gt; eventHandler, T args) where T : EventArgs\n{\n    if (eventHandler == null) return;\n\n    foreach (EventHandler&lt;T&gt; singleEvent in eventHandler.GetInvocationList())\n    {\n        if (singleEvent.Target != null &amp;&amp; singleEvent.Target is ISynchronizeInvoke)\n        {\n            var target = (ISynchronizeInvoke)singleEvent.Target;\n\n            if (target.InvokeRequired) {\n                target.BeginInvoke(singleEvent, new object[] { this, args });\n                continue;\n            }\n        }\n        singleEvent(this, args);\n    }\n}\n</code></pre>\n\n<p>and here is an example usage:</p>\n\n<pre><code>public event EventHandler&lt;ProgressEventArgs&gt; ProgressChanged;\n\nprivate void OnProgressChanged(int processed, int total)\n{\n    OnEvent(ProgressChanged, new ProgressEventArgs(processed, total));\n}\n</code></pre>\n'}, {'answer_id': 1242225, 'author': 'JoshL', 'author_id': 20625, 'author_profile': 'https://Stackoverflow.com/users/20625', 'pm_score': 3, 'selected': False, 'text': '<p>Expression to initialize a Dictionary in C# 3.5:</p>\n\n<p><code>new Dictionary&lt;string, Int64&gt;() {{"Testing", 123}, {"Test", 125}};</code></p>\n'}, {'answer_id': 1243242, 'author': 'ata', 'author_id': 150830, 'author_profile': 'https://Stackoverflow.com/users/150830', 'pm_score': 3, 'selected': False, 'text': "<p>I don't think someone has mentioned that appending ? after a value type name will make it nullable.</p>\n\n<p>You can do: </p>\n\n<pre><code>DateTime? date = null;\n</code></pre>\n\n<p>DateTime is a structure.</p>\n"}, {'answer_id': 1243265, 'author': 'Jason Williams', 'author_id': 97385, 'author_profile': 'https://Stackoverflow.com/users/97385', 'pm_score': 5, 'selected': False, 'text': '<p>Programmers moving from C/C++ may miss this one:</p>\n\n<p>In C#, % (modulus operator) works on floats!</p>\n'}, {'answer_id': 1247323, 'author': 'paracycle', 'author_id': 98634, 'author_profile': 'https://Stackoverflow.com/users/98634', 'pm_score': 2, 'selected': False, 'text': '<p>Generics and the <a href="http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="nofollow noreferrer">Curiously-Recurring Template Pattern</a> really help with some static method/property declarations.</p>\n\n<p>Suppose you are building a class hierarchy:</p>\n\n<pre><code>class Base\n{\n}\n\nclass Foo: Base\n{\n}\n\nclass Bar: Base\n{\n}\n</code></pre>\n\n<p>Now, you want to declare static methods on your types that should take parameters (or return values) of the same type or static properties of the same type. For example, you want:</p>\n\n<pre><code>class Base\n{\n    public static Base Get()\n    {\n        // Return a suitable Base.\n    }\n}\n\nclass Foo: Base\n{\n    public static Foo Get()\n    {\n        // Return a suitable Foo.\n    }\n}\n\nclass Bar: Base\n{\n    public static Bar Get()\n    {\n        // Return a suitable Bar.\n    }\n}\n</code></pre>\n\n<p>If these static methods basically all do the same thing, then you have lots of duplicated code on your hands. One solution would be to drop type safety on the return values and to always return type <code>Base</code>. However, if you want type safety, then the solution is to declare the <code>Base</code> as:</p>\n\n<pre><code>class Base&lt;T&gt; where T: Base&lt;T&gt;\n{\n    public static T Get&lt;T&gt;()\n    {\n        // Return a suitable T.\n    }\n}\n</code></pre>\n\n<p>and you <code>Foo</code> and <code>Bar</code> as:</p>\n\n<pre><code>class Foo: Base&lt;Foo&gt;\n{\n}\n\nclass Bar: Base&lt;Bar&gt;\n{\n}\n</code></pre>\n\n<p>This way, they will automatically get their <strong>copies</strong> of the static methods.</p>\n\n<p>This also works wonders to encapsulate the <strong>Singleton</strong> pattern in a base class (I know the code below is not thread-safe, it just to demonstrate a point):</p>\n\n<pre><code>public class Singleton&lt;T&gt; where T: Singleton&lt;T&gt;, new()\n{\n  public static T Instance { get; private set; }\n\n  static Singleton&lt;T&gt;()\n  {\n    Instance = new T();\n  }\n}\n</code></pre>\n\n<p>I realize that this forces you to have a public parameterless constructor on your singleton subclass but there is no way to avoid that at compile time without a <code>where T: protected new()</code> construct; however one can use <a href="http://www.codeproject.com/KB/architecture/GenericSingletonPattern.aspx" rel="nofollow noreferrer">reflection</a> to invoke the protected/private parameterless constructor of the sub-class at runtime to achieve that.</p>\n'}, {'answer_id': 1277525, 'author': 'Ali Ersöz', 'author_id': 4215, 'author_profile': 'https://Stackoverflow.com/users/4215', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://blogs.msdn.com/ericlippert/archive/2009/08/13/four-switch-oddities.aspx" rel="nofollow noreferrer">Four switch oddities</a> by Eric Lippert</p>\n'}, {'answer_id': 1280160, 'author': 'Maslow', 'author_id': 57883, 'author_profile': 'https://Stackoverflow.com/users/57883', 'pm_score': 2, 'selected': False, 'text': '<p>Keeps DataGridView from showing the property:</p>\n\n<pre><code>[System.ComponentModel.Browsable(false)]\npublic String LastActionID{get; private set;}\n</code></pre>\n\n<p>Lets you set a friendly display for components (like a DataGrid or DataGridView):</p>\n\n<pre><code>[System.ComponentModel.DisplayName("Last Action")]\npublic String LastAction{get; private set;}\n</code></pre>\n\n<p>For your backing variables, if you don\'t want anything accessing them directly this makes it tougher:</p>\n\n<pre><code>[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n    private DataController p_dataSources;\n</code></pre>\n'}, {'answer_id': 1311431, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>The ability to use LINQ to do inline work on collections that used to take iteration and conditionals can be incredibly valuable. It's worth learning how all the LINQ extension methods can help make your code much more compact and maintainable.</p>\n"}, {'answer_id': 1318297, 'author': 'mezoid', 'author_id': 39532, 'author_profile': 'https://Stackoverflow.com/users/39532', 'pm_score': 3, 'selected': False, 'text': '<p>One that I just learned recently is that you can still call <a href="https://stackoverflow.com/questions/1242883/is-there-a-better-way-to-write-this-line-of-c-code-in-c3-0">methods on a nullable value</a>....</p>\n\n<p>It turns out what when you have a nullable value:</p>\n\n<pre><code>decimal? MyValue = null;\n</code></pre>\n\n<p>where you might think you would have to write:</p>\n\n<pre><code>MyValue == null ? null : MyValue .ToString()\n</code></pre>\n\n<p>you can instead write:</p>\n\n<pre><code>MyValue.ToString()\n</code></pre>\n\n<p>I\'ve been aware that I could call MyValue.HasValue and MyValue.Value...but it didn\'t fully click that I could call ToString().</p>\n'}, {'answer_id': 1371317, 'author': 'manji', 'author_id': 166538, 'author_profile': 'https://Stackoverflow.com/users/166538', 'pm_score': 3, 'selected': False, 'text': "<p>This will not compile:</p>\n\n<pre><code>namespace ns\n{\n    class Class1\n    {\n        Nullable&lt;int&gt; a;\n    }\n}\n</code></pre>\n\n<p><em>The type or namespace name 'Nullable' could not be found (are you missing a using directive or an assembly reference?)</em> &lt;-- missing '<code>using System;</code>'</p>\n\n<p>But</p>\n\n<pre><code>namespace ns\n{\n    class Class1\n    {\n        int? a;\n    }\n}\n</code></pre>\n\n<p>will compile! (.NET 2.0).</p>\n"}, {'answer_id': 1399045, 'author': 'jpierson', 'author_id': 83658, 'author_profile': 'https://Stackoverflow.com/users/83658', 'pm_score': 3, 'selected': False, 'text': '<p>Nested classes can access private members of a outer class.</p>\n\n<pre><code>public class Outer\n{\n    private int Value { get; set; }\n\n    public class Inner\n    {\n        protected void ModifyOuterMember(Outer outer, int value)\n        {\n            outer.Value = value;\n        }\n    }\n}\n</code></pre>\n\n<p>And now together with the above feature you can also inherit from nested classes as if they were top level classes as shown below.</p>\n\n<pre><code>public class Cheater : Outer.Inner\n{\n    protected void MakeValue5(Outer outer)\n    {\n        ModifyOuterMember(outer, 5);\n    }\n}\n</code></pre>\n\n<p>These features allow for some interesting possibilities as far as providing access to particular members via somewhat hidden classes.</p>\n'}, {'answer_id': 1399130, 'author': 'cllpse', 'author_id': 20946, 'author_profile': 'https://Stackoverflow.com/users/20946', 'pm_score': 5, 'selected': False, 'text': '<p><strong>JavaScript-like anonymous inline-functions</strong></p>\n\n<p>Return a String:</p>\n\n<pre><code>var s = new Func&lt;String&gt;(() =&gt;\n{\n    return "Hello World!";\n})();\n</code></pre>\n\n<p>Return a more complex Object:</p>\n\n<pre><code>var d = new Func&lt;Dictionary&lt;Int32, String&gt;&gt;(() =&gt;\n{\n    return new Dictionary&lt;Int32, String&gt;\n    {\n        { 0, "Foo" },\n        { 1, "Bar" },\n        { 2, "..." }\n    };\n})();\n</code></pre>\n\n<p>A real-world use-case:</p>\n\n<pre><code>var tr = new TableRow();\n\ntr.Cells.AddRange\n(\n    new[]\n    {\n        new TableCell { Text = "" },\n        new TableCell { Text = "" },\n        new TableCell { Text = "" },\n\n        new TableCell\n        {\n            Text = new Func&lt;String&gt;(() =&gt;\n            {\n                return @"Result of a chunk of logic, without having to define\n                         the logic outside of the TableCell constructor";\n            })()\n        },\n\n        new TableCell { Text = "" },\n        new TableCell { Text = "" }\n    }\n);\n</code></pre>\n\n<p><em>Note: You cannot re-use variable names inside the inline-function\'s scope.</em></p>\n\n<p><br /></p>\n\n<p><strong>Alternative syntax</strong></p>\n\n<pre><code>// The one-liner\nFunc&lt;Int32, Int32, String&gt; Add = (a, b) =&gt; Convert.ToString(a + b);\n\n// Multiple lines\nFunc&lt;Int32, Int32, String&gt; Add = (a, b) =&gt;\n{\n    var i = a + b;\n\n    return i.ToString();\n};\n\n// Without parameters\nFunc&lt;String&gt; Foo = () =&gt; "";\n\n// Without parameters, multiple lines\nFunc&lt;String&gt; Foo = () =&gt;\n{\n    return "";\n};\n</code></pre>\n\n<p>Shorten a string and add horizontal ellipsis...</p>\n\n<pre><code>Func&lt;String, String&gt; Shorten = s =&gt; s.Length &gt; 100 ? s.Substring(0, 100) + "&amp;hellip;" : s;\n</code></pre>\n'}, {'answer_id': 1404712, 'author': 'madcyree', 'author_id': 167809, 'author_profile': 'https://Stackoverflow.com/users/167809', 'pm_score': 2, 'selected': False, 'text': '<p>At first - <a href="http://msdn.microsoft.com/en-us/library/d8eyd8zc.aspx" rel="nofollow noreferrer">DebuggerTypeProxy</a>.</p>\n\n<pre><code>[DebuggerTypeProxy(typeof(HashtableDebugView))]\nclass MyHashtable : Hashtable\n{\n    private const string TestString = \n        "This should not appear in the debug window.";\n\n    internal class HashtableDebugView\n    {\n        private Hashtable hashtable;\n        public const string TestStringProxy = \n            "This should appear in the debug window.";\n\n        // The constructor for the type proxy class must have a \n        // constructor that takes the target type as a parameter.\n        public HashtableDebugView(Hashtable hashtable)\n        {\n            this.hashtable = hashtable;\n        }\n    }\n}\n</code></pre>\n\n<p>At second:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/ms171819.aspx" rel="nofollow noreferrer">ICustomTypeDescriptor</a></p>\n'}, {'answer_id': 1408887, 'author': 'Todd Richardson', 'author_id': 93964, 'author_profile': 'https://Stackoverflow.com/users/93964', 'pm_score': 3, 'selected': False, 'text': '<p>I apologize if this one has been mentioned, but I use this a lot.  </p>\n\n<p>An add-in for Visual Studio was developed by Alex Papadimoulis.  It\'s used for pasting regular text as string, string builder, comment or region.</p>\n\n<p><a href="http://weblogs.asp.net/alex_papadimoulis/archive/2004/05/25/Smart-Paster-1.1-Add-In---StringBuilder-and-Better-C_2300_-Handling.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/alex_papadimoulis/archive/2004/05/25/Smart-Paster-1.1-Add-In---StringBuilder-and-Better-C_2300_-Handling.aspx</a></p>\n\n<p>In this plugin (I also don\'t know if this has been mentioned) I noticed that strings are pasted with the string literal prefix:</p>\n\n<pre><code>@\n</code></pre>\n\n<p>I knew about these, but I didn\'t know about using a double quote within a literal to escape the quote.  </p>\n\n<p>For example</p>\n\n<pre><code>string s = "A line of text" + Environment.NewLine + "Another with a \\"quote\\"!!";\n</code></pre>\n\n<p>can be expressed as</p>\n\n<pre><code>string s = @"A line of text \nAnother with a ""quote""!!";\n</code></pre>\n'}, {'answer_id': 1415909, 'author': 'codymanix', 'author_id': 44952, 'author_profile': 'https://Stackoverflow.com/users/44952', 'pm_score': 4, 'selected': False, 'text': '<p>When defining custom attributes you can use them with [MyAttAttribute] or with [MyAtt].\nWhen classes exist for both writings, then a compilation error occures.</p>\n\n<p>The @ special character can be used to distinguish between them:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.All)]\npublic class X: Attribute\n{}\n\n[AttributeUsage(AttributeTargets.All)]\npublic class XAttribute: Attribute\n{}\n\n[X]      // Error: ambiguity\nclass Class1 {}\n\n[XAttribute]   // Refers to XAttribute\nclass Class2 {}\n\n[@X]      // Refers to X\nclass Class3 {}\n\n[@XAttribute]   // Refers to XAttribute\nclass Class4 {}\n</code></pre>\n'}, {'answer_id': 1415952, 'author': 'codymanix', 'author_id': 44952, 'author_profile': 'https://Stackoverflow.com/users/44952', 'pm_score': 5, 'selected': False, 'text': '<p>You can "use" multiple objects in one using statement.</p>\n\n<pre><code>using (Font f1= new Font("Arial", 10.0f), f2 = new Font("Arial", 10.0f))\n{\n    // Use f1 and f2.\n}\n</code></pre>\n\n<p>Note that there is already an answer stating that you can do this:</p>\n\n<pre><code>using (Font f1= new Font("Arial", 10.0f))\nusing (Font f2 = new Font("Arial", 10.0f))\n{    }\n</code></pre>\n\n<p>Which is different from mine.</p>\n'}, {'answer_id': 1416182, 'author': 'Oliver', 'author_id': 67494, 'author_profile': 'https://Stackoverflow.com/users/67494', 'pm_score': 2, 'selected': False, 'text': "<p>Not sure Microsoft would like this question, especially with so many responses. \nI'm sure I once heard a Microsoft head say:</p>\n\n<blockquote>\n  <p>a hidden feature is a wasted feature</p>\n</blockquote>\n\n<p>... or something to that effect.</p>\n"}, {'answer_id': 1435045, 'author': 'Keith Adler', 'author_id': 135952, 'author_profile': 'https://Stackoverflow.com/users/135952', 'pm_score': 4, 'selected': False, 'text': '<p>You can limit the life and thus scope of variables by using <code>{ }</code> brackets.</p>\n\n<pre><code>{\n    string test2 = "3";\n    Console.Write(test2);\n}\n\nConsole.Write(test2); //compile error\n</code></pre>\n\n<p><code>test2</code> only lives within the brackets.</p>\n'}, {'answer_id': 1464831, 'author': 'rikoe', 'author_id': 177117, 'author_profile': 'https://Stackoverflow.com/users/177117', 'pm_score': 4, 'selected': False, 'text': "<p>Apologies for posting so late, I am new to Stack Overflow so missed the earlier opportunity.</p>\n\n<p>I find that <code>EventHandler&lt;T&gt;</code> is a great feature of the framework that is underutilised. </p>\n\n<p>Most C# developers I come across still define a custom event handler delegate when they are defining custom events, which is simply not necessary anymore.</p>\n\n<p>Instead of:</p>\n\n<pre><code>public delegate void MyCustomEventHandler(object sender, MyCustomEventArgs e);\n\npublic class MyCustomEventClass \n{\n    public event MyCustomEventHandler MyCustomEvent;\n}\n</code></pre>\n\n<p>you can go:</p>\n\n<pre><code>public class MyCustomEventClass \n{\n    public event EventHandler&lt;MyCustomEventArgs&gt; MyCustomEvent;\n}\n</code></pre>\n\n<p>which is a lot more concise, plus you don't get into the dilemma of whether to put the delegate in the .cs file for the class that contains the event, or the EventArgs derived class.</p>\n"}, {'answer_id': 1484202, 'author': 'Mike Valenty', 'author_id': 124839, 'author_profile': 'https://Stackoverflow.com/users/124839', 'pm_score': 3, 'selected': False, 'text': '<p>Open generics are another handy feature especially when using <a href="http://en.wikipedia.org/wiki/Inversion_of_control" rel="nofollow noreferrer">Inversion of Control</a>:</p>\n\n<pre><code>container.RegisterType(typeof(IRepository&lt;&gt;), typeof(NHibernateRepository&lt;&gt;));\n</code></pre>\n'}, {'answer_id': 1593594, 'author': 'Himadri', 'author_id': 173655, 'author_profile': 'https://Stackoverflow.com/users/173655', 'pm_score': 2, 'selected': False, 'text': '<p>Use of @ before a string that contains escape char.\nBasically when a physical path is used to assign in a string variable everybody uses \'\\\' where escape character is present in a string.</p>\n\n<p>e.g.\nstring strPath="D:\\websites\\web1\\images\\";</p>\n\n<p>But escape characters can be ignored using @ before the string value. </p>\n\n<p>e.g. \nstring strPath=@"D:\\websites\\web1\\images\\";</p>\n'}, {'answer_id': 1625860, 'author': 'Florian Doyon', 'author_id': 91585, 'author_profile': 'https://Stackoverflow.com/users/91585', 'pm_score': 2, 'selected': False, 'text': "<p>I love abusing the fact that static templated classes don't share their static members.</p>\n\n<p>Here's a threadsafe (at creation time) and cheap substitute to any <code>Dictionary&lt;Type,...&gt;</code> when the <code>Type</code> instance is known at compile-time.</p>\n\n<pre><code>public static class MyCachedData&lt;T&gt;{\n    static readonly CachedData Value;\n    static MyCachedData(){\n       Value=// Heavy computation, such as baking IL code or doing lots of reflection on a type\n    }\n}\n</code></pre>\n\n<p>Cheers,\nFlorian</p>\n"}, {'answer_id': 1647219, 'author': 'Lyubomyr Shaydariv', 'author_id': 166589, 'author_profile': 'https://Stackoverflow.com/users/166589', 'pm_score': 2, 'selected': False, 'text': '<p>The following one is not hidden, but it\'s quite implicit. I don\'t know whether samples like the following one have been published here, and I can\'t see are there any benefits (probably there are none), but I\'ll try to show a "weird" code. The following sample simulates <code>for</code> statement via functors in C# (delegates / anonymous delegates [lambdas]) and closures. Other flow statements like <code>if</code>, <code>if/else</code>, <code>while</code> and <code>do/whle</code>  are simulated as well, but I\'m not sure for <code>switch</code> (perhaps, I\'m too lazy :)). I\'ve compacted the sample source code a little to make it more clear.</p>\n\n<pre><code>private static readonly Action EmptyAction = () =&gt; { };\nprivate static readonly Func&lt;bool&gt; EmptyCondition = () =&gt; { return true; };\n\nprivate sealed class BreakStatementException : Exception { }\nprivate sealed class ContinueStatementException : Exception { }\nprivate static void Break() { throw new BreakStatementException(); }\nprivate static void Continue() { throw new ContinueStatementException(); }\n\nprivate static void For(Action init, Func&lt;bool&gt; condition, Action postBlock, Action statement) {\n    init = init ?? EmptyAction;\n    condition = condition ?? EmptyCondition;\n    postBlock = postBlock ?? EmptyAction;\n    statement = statement ?? EmptyAction;\n    for ( init(); condition(); postBlock() ) {\n        try {\n            statement();\n        } catch ( BreakStatementException ) {\n            break;\n        } catch ( ContinueStatementException ) {\n            continue;\n        }\n    }\n}\n\nprivate static void Main() {\n    int i = 0; // avoiding error "Use of unassigned local variable \'i\'" if not using `for` init block\n    For(() =&gt; i = 0, () =&gt; i &lt; 10, () =&gt; i++,\n        () =&gt; {\n            if ( i == 5 )\n                Continue();\n            Console.WriteLine(i);\n        }\n    );\n}\n</code></pre>\n\n<p>If I\'m not wrong, this approach is pretty relative to the functional programming practice. Am I right?</p>\n'}, {'answer_id': 1677556, 'author': 'plaureano', 'author_id': 46265, 'author_profile': 'https://Stackoverflow.com/users/46265', 'pm_score': 3, 'selected': False, 'text': "<p>C# allows you to add property setter methods to concrete types that implement readonly interface properties even though the interface declaration itself has no property setter. For example:</p>\n\n<pre><code>public interface IReadOnlyFoo\n{\n   object SomeReadOnlyProperty { get; }\n}\n</code></pre>\n\n<p>The concrete class looks like this:</p>\n\n<pre><code>internal class Foo : IReadOnlyFoo\n{\n   public object SomeReadOnlyProperty { get; internal set; }\n}\n</code></pre>\n\n<p>What's interesting about this is that the Foo class is immutable if you cast it to the IReadOnlyFoo interface:</p>\n\n<pre><code>// Create a Foo instance\nFoo foo = new Foo();\n\n// This statement is legal\nfoo.SomeReadOnlyProperty = 12345;\n\n// Make Foo read only\nIReadOnlyFoo readOnlyFoo = foo;\n\n// This statement won't compile\nreadOnlyFoo.SomeReadOnlyProperty = 54321;\n</code></pre>\n"}, {'answer_id': 1699477, 'author': 'Himadri', 'author_id': 173655, 'author_profile': 'https://Stackoverflow.com/users/173655', 'pm_score': 6, 'selected': False, 'text': '<p>I just wanted to copy that code without the comments. So, the trick is to simply press the Alt button, and then highlight the rectangle you like.(e. g. below).</p>\n\n<pre><code>protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)\n    {\n        //if (e.CommandName == "sel")\n        //{\n        //    lblCat.Text = e.CommandArgument.ToString();\n        //}\n    }\n</code></pre>\n\n<p>In the above code if I want to select :</p>\n\n<pre><code>e.CommandName == "sel"\n\nlblCat.Text = e.Comman\n</code></pre>\n\n<p>Then I press ALt key and select the rectangle and no need to uncomment the lines.</p>\n\n<p>Check this out.</p>\n'}, {'answer_id': 1707290, 'author': 'Shital Shah', 'author_id': 207661, 'author_profile': 'https://Stackoverflow.com/users/207661', 'pm_score': 5, 'selected': False, 'text': '<p>C# + CLR:</p>\n\n<ol>\n<li><p><code>Thread.MemoryBarrier</code>: Most people wouldn\'t have used it and there is some inaccurate information on MSDN. But if you know <a href="http://www.albahari.com/threading/part4.aspx" rel="noreferrer">intricacies</a> then you can do nifty lock-free synchronization.</p></li>\n<li><p><code>volatile, Thread.VolatileRead, Thread.VolatileWrite</code>: There are very very few people who gets the use of these and even fewer who understands all the risks they avoid and introduce :).</p></li>\n<li><p><code>ThreadStatic</code> variables: There was only one situation in past few years I\'ve found that ThreadStatic variables were absolutely god send and indispensable. When you want to do something for entire call chain, for example, they are very useful.</p></li>\n<li><p><code>fixed</code> keyword: It\'s a hidden weapon when you want to make access to elements of large array almost as fast as C++ (by default C# enforces bound checks that slows down things).</p></li>\n<li><p><code>default(typeName)</code> keyword can be used outside of generic class as well. It\'s useful to create empty copy of struct.</p></li>\n<li><p>One of the handy feature I use is <code>DataRow[columnName].ToString()</code> always returns non-null value. If value in database was NULL, you get empty string.</p></li>\n<li><p>Use Debugger object to break automatically when you want developer\'s attention even if s/he hasn\'t enabled automatic break on exception:</p></li>\n</ol>\n\n<pre><code>\n#if DEBUG  \n    if (Debugger.IsAttached)  \n        Debugger.Break();  \n#endif\n</code></pre>\n\n<ol start="8">\n<li>You can alias complicated ugly looking generic types so you don\'t have to copy paste them again and again. Also you can make changes to that type in one place. For example, </li>\n</ol>\n\n<pre><code>\n    using ComplicatedDictionary = Dictionary&lt;int, Dictionary&lt;string, object>>;\n    ComplicatedDictionary myDictionary = new ComplicatedDictionary();\n</code></pre>\n'}, {'answer_id': 1724852, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Need to return an empty IEnumerable?</p>\n\n<pre><code>public IEnumerable&lt;T&gt; GetEnumerator(){\n  yield break;\n}\n</code></pre>\n'}, {'answer_id': 1770965, 'author': 'thr', 'author_id': 452521, 'author_profile': 'https://Stackoverflow.com/users/452521', 'pm_score': 4, 'selected': False, 'text': '<h1>Type-inference for factory methods</h1>\n\n<p><em>I don\'t know if this has been posted already (I scanned the first post, couldn\'t find it).</em></p>\n\n<p>This is best shown with an example, assuming you have this class (to simulate a tuple), in in an attempt to demonstrate all the language features that make this possible I will go through it step by step.</p>\n\n<pre><code>public class Tuple&lt;V1, V2&gt; : Tuple\n{\n    public readonly V1 v1;\n    public readonly V2 v2;\n\n    public Tuple(V1 v1, V2 v2)\n    {\n      this.v1 = v1;\n      this.v2 = v2;\n    }\n}\n</code></pre>\n\n<p>Everyone knows how to create an instance of it, such as:</p>\n\n<pre><code>Tuple&lt;int, string&gt; tup = new Tuple&lt;int, string&gt;(1, "Hello, World!");\n</code></pre>\n\n<p>Not exactly rocket science, now we can of course change the type declaration of the variable to <em>var</em>, like this:</p>\n\n<pre><code>var tup = new Tuple&lt;int, string&gt;(1, "Hello, World!");\n</code></pre>\n\n<p>Still well known, to digress a bit here\'s a static method with type parameters, which everyone should be familiar with:</p>\n\n<pre><code>public static void Create&lt;T1, T2&gt;()\n{\n    // stuff\n}\n</code></pre>\n\n<p>Calling it is, again common knowledge, done like this:</p>\n\n<pre><code>Create&lt;float, double&gt;();\n</code></pre>\n\n<p>What most people don\'t know is that if the arguments to the generic method contains all the types it requires they can be inferred, for example:</p>\n\n<pre><code>public static void Create&lt;T1, T2&gt;(T1 a, T2 b)\n{\n    // stuff\n}\n</code></pre>\n\n<p>These two calls are identical:</p>\n\n<pre><code>Create&lt;float, string&gt;(1.0f, "test");\nCreate(1.0f, "test");\n</code></pre>\n\n<p>Since T1 and T2 is inferred from the arguments you passed. Combining this knowledge with the var keyword, we can by adding a second static class with a static method, such as:</p>\n\n<pre><code>public abstract class Tuple\n{\n    public static Tuple&lt;V1, V2&gt; Create&lt;V1, V2&gt;(V1 v1, V2 v2)\n    {\n        return new Tuple&lt;V1, V2&gt;(v1, v2);\n    }\n}\n</code></pre>\n\n<p>Achieve this effect:</p>\n\n<pre><code>var tup = Tuple.Create(1, "Hello, World!");\n</code></pre>\n\n<p>This means that the types of the: variable "tup", the type-parameters of "Create" and the return value of "Create" are all inferred from the types you <strong>pass as arguments to Create</strong></p>\n\n<p>The full code looks something like this:</p>\n\n<pre><code>public abstract class Tuple\n{\n    public static Tuple&lt;V1, V2&gt; Create&lt;V1, V2&gt;(V1 v1, V2 v2)\n    {\n        return new Tuple&lt;V1, V2&gt;(v1, v2);\n    }\n}\n\npublic class Tuple&lt;V1, V2&gt; : Tuple\n{\n    public readonly V1 v1;\n    public readonly V2 v2;\n\n    public Tuple(V1 v1, V2 v2)\n    {\n        this.v1 = v1;\n        this.v2 = v2;\n    }\n}\n\n// Example usage:\nvar tup = Tuple.Create(1, "test");\n</code></pre>\n\n<p>Which gives you fully type inferred factory methods everywhere!</p>\n'}, {'answer_id': 1774916, 'author': 'Brian', 'author_id': 320, 'author_profile': 'https://Stackoverflow.com/users/320', 'pm_score': 3, 'selected': False, 'text': '<p>I like the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx" rel="nofollow noreferrer">EditorBrowsableAttribute</a>. It lets you control whether a method/property is displayed or not in Intellisense. You can set the values to Always, Advanced, or Never.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx" rel="nofollow noreferrer">From MSDN</a>...</p>\n\n<p><strong>Remarks</strong></p>\n\n<p>EditorBrowsableAttribute is a hint to a designer indicating whether a property or method is to be displayed. You can use this type in a visual designer or text editor to determine what is visible to the user. For example, the IntelliSense engine in Visual Studio uses this attribute to determine whether to show a property or method.</p>\n\n<p>In Visual C#, you can control when advanced properties appear in IntelliSense and the Properties Window with the Hide Advanced Members setting under Tools | Options | Text Editor | C#. The corresponding EditorBrowsableState is Advanced.</p>\n'}, {'answer_id': 1789985, 'author': 'Roman Boiko', 'author_id': 118478, 'author_profile': 'https://Stackoverflow.com/users/118478', 'pm_score': 5, 'selected': False, 'text': '<p>Easily determine type with which variable was <strong>declared</strong> (from <a href="https://stackoverflow.com/questions/1786750/how-to-know-in-c-code-which-type-a-variable-was-declared-with/1786775#1786775" title="Determine declared type of a variable">my answer</a>):</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nstatic class Program\n{\n    public static Type GetDeclaredType&lt;T&gt;(T x)\n    {\n        return typeof(T);\n    }\n\n    // Demonstrate how GetDeclaredType works\n    static void Main(string[] args)\n    {\n        IList&lt;string&gt; iList = new List&lt;string&gt;();\n        List&lt;string&gt; list = null;\n\n        Console.WriteLine(GetDeclaredType(iList).Name);\n        Console.WriteLine(GetDeclaredType(list).Name);\n    }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>IList`1\nList`1\n</code></pre>\n\n<p>And its <strong>name</strong> (borrowed from <a href="https://stackoverflow.com/questions/1386642/get-variable-not-hard-coded-name/1386730#1386730" title="Get variable name">"Get variable name"</a>):</p>\n\n<pre><code>static void Main(string[] args)\n{\n    Console.WriteLine("Name is \'{0}\'", GetName(new {args}));\n    Console.ReadLine();\n}\n\nstatic string GetName&lt;T&gt;(T item) where T : class\n{\n    var properties = typeof(T).GetProperties();\n    return properties[0].Name;\n}\n</code></pre>\n\n<p>Result: <code>Name is \'args\'</code></p>\n'}, {'answer_id': 1798482, 'author': 'Phillip Ngan', 'author_id': 41410, 'author_profile': 'https://Stackoverflow.com/users/41410', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Convert enum values to a string value</strong></p>\n\n<p>Given the enum</p>\n\n<pre><code>enum Country\n{\n    UnitedKingdom, \n    UnitedStates,\n    UnitedArabEmirates,\n}\n</code></pre>\n\n<p>using it:</p>\n\n<pre><code>public static void PrintEnumAsString( Country country )\n{\n    Console.Writeline( country.ToString() );\n}\n</code></pre>\n\n<p>will print the name of the enum value as a string, e.g. "UnitedKingdom"</p>\n'}, {'answer_id': 1820538, 'author': 'Roman Boiko', 'author_id': 118478, 'author_profile': 'https://Stackoverflow.com/users/118478', 'pm_score': 5, 'selected': False, 'text': '<p>I found that only few developers know about this feature.</p>\n\n<p>If you need a method that works with a <strong>value-type variable via some interface</strong> (implemented by this value type), it\'s easy to <strong>avoid boxing</strong> during the method call.</p>\n\n<p>Example code:</p>\n\n<pre><code>using System;\nusing System.Collections;\n\ninterface IFoo {\n    void Foo();\n}\nstruct MyStructure : IFoo {\n    public void Foo() {\n    }\n}\npublic static class Program {\n    static void MethodDoesNotBoxArguments&lt;T&gt;(T t) where T : IFoo {\n        t.Foo();\n    }\n    static void Main(string[] args) {\n        MyStructure s = new MyStructure();\n        MethodThatDoesNotBoxArguments(s);\n    }\n}\n</code></pre>\n\n<p>IL code doesn\'t contain any box instructions:</p>\n\n<pre><code>.method private hidebysig static void  MethodDoesNotBoxArguments&lt;(IFoo) T&gt;(!!T t) cil managed\n{\n  // Code size       14 (0xe)\n  .maxstack  8\n  IL_0000:  ldarga.s   t\n  IL_0002:  constrained. !!T\n  IL_0008:  callvirt   instance void IFoo::Foo()\n  IL_000d:  ret\n} // end of method Program::MethodDoesNotBoxArguments\n\n.method private hidebysig static void  Main(string[] args) cil managed\n{\n  .entrypoint\n  // Code size       15 (0xf)\n  .maxstack  1\n  .locals init ([0] valuetype MyStructure s)\n  IL_0000:  ldloca.s   s\n  IL_0002:  initobj    MyStructure\n  IL_0008:  ldloc.0\n  IL_0009:  call       void Program::MethodDoesNotBoxArguments&lt;valuetype MyStructure&gt;(!!0)\n  IL_000e:  ret\n} // end of method Program::Main\n</code></pre>\n\n<p>See <a href="http://rads.stackoverflow.com/amzn/click/0735621632" rel="nofollow noreferrer">Richter, J. CLR via C#</a>, 2nd edition, chapter 14: Interfaces, section about Generics and Interface Constraints.</p>\n\n<p>See also <a href="https://stackoverflow.com/questions/1816419/does-passing-a-struct-into-an-interface-field-allocate/1817137#1817137">my answer</a> to another question.</p>\n'}, {'answer_id': 1821257, 'author': 'Paul Ruane', 'author_id': 83264, 'author_profile': 'https://Stackoverflow.com/users/83264', 'pm_score': 4, 'selected': False, 'text': "<p>A couple I can think of:</p>\n\n<pre><code>[field: NonSerialized()]\npublic EventHandler event SomeEvent;\n</code></pre>\n\n<p>This prevents the event from being serialised.  The 'field:' indicates that the attribute should be applied to the event's backing field.</p>\n\n<p>Another little known feature is overriding the add/remove event handlers:</p>\n\n<pre><code>public event EventHandler SomeEvent\n{\n    add\n    {\n        // ...\n    }\n\n    remove\n    {\n        // ...\n    }\n}\n</code></pre>\n"}, {'answer_id': 1836944, 'author': 'Zac Bowling', 'author_id': 171819, 'author_profile': 'https://Stackoverflow.com/users/171819', 'pm_score': 3, 'selected': False, 'text': '<p>__arglist as well</p>\n\n<pre><code>[DllImport("msvcrt40.dll")]\npublic static extern int printf(string format, __arglist);\n\nstatic void Main(string[] args)\n{\n   printf("Hello %s!\\n", __arglist("Bart"));\n}\n</code></pre>\n'}, {'answer_id': 1858602, 'author': 'Matt Dotson', 'author_id': 226060, 'author_profile': 'https://Stackoverflow.com/users/226060', 'pm_score': 3, 'selected': False, 'text': '<p>Dictionary initializers are always useful for quick hacks and unit tests where you need to hardcode some data.</p>\n\n<pre><code>var dict = new Dictionary&lt;int, string&gt; { { 10, "Hello" }, { 20, "World" } };\n</code></pre>\n'}, {'answer_id': 1962004, 'author': 'Dave Jellison', 'author_id': 184725, 'author_profile': 'https://Stackoverflow.com/users/184725', 'pm_score': 3, 'selected': False, 'text': '<p>The Action and Func delegate helpers in conjunction with lambda methods. I use these for simple patterns that need a delegate to improve readability. For example, a simple caching pattern would be to check if the requested object exists in the cache. If it does exist: return the cached object. If it doesn\'t exist, generate a new instance, cache the new instance and return the new instance. Rather that write this code 1000 times for each object I may store/retrieve from the cache I can write a simple pattern method like so...</p>\n\n<pre><code>private static T CachePattern&lt;T&gt;(string key, Func&lt;T&gt; create) where T : class\n{\n    if (cache[key] == null)\n    {\n        cache.Add(key, create());\n    }\n\n    return cache[key] as T;\n}\n</code></pre>\n\n<p>... then I can greatly simplify my cache get/set code by using the following in my custom cache manager</p>\n\n<pre><code>public static IUser CurrentUser\n{\n    get\n    {\n        return CachePattern&lt;IUser&gt;("CurrentUserKey", () =&gt; repository.NewUpUser());\n    }\n}\n</code></pre>\n\n<p>Now simple "everyday" code patterns can be written once and reused much more easily IMHO. I don\'t have to go write a delegate type and figure out how I want to implement a callback, etc. If I can write it in 10 seconds I\'m much less apt. to resort to cutting/pasting simple code patterns whether they be lazy initialization and some other examples shown above...</p>\n'}, {'answer_id': 1977121, 'author': 'Jerod Venema', 'author_id': 25330, 'author_profile': 'https://Stackoverflow.com/users/25330', 'pm_score': 2, 'selected': False, 'text': '<p>The "TODO" property and the tasks list</p>\n\n<pre><code>//TODO: [something] \n</code></pre>\n\n<p>Adding that to your code (the spacing is important) throws an item in your task list, and double clicking the item will jump you to the appropriate location in your code.</p>\n'}, {'answer_id': 2005795, 'author': 'Ravi Vanapalli', 'author_id': 188822, 'author_profile': 'https://Stackoverflow.com/users/188822', 'pm_score': 2, 'selected': False, 'text': "<p>I didn't knew about Generic methods which could help avoid using Method Overloadding.\nBelow are overloaded methods to print int and double numbers.</p>\n\n<pre><code>    private static void printNumbers(int [] intNumbers)\n    { \n        foreach(int element in intNumbers)\n        {\n            Console.WriteLine(element);\n        }\n\n    }\n\n    private static void printNumbers(double[] doubleNumbers)\n    {\n        foreach (double element in doubleNumbers)\n        {\n            Console.WriteLine(element);\n        }\n    }\n</code></pre>\n\n<p>Generic method which help to have one method for both of the above</p>\n\n<pre><code>    private static void printNumbers&lt;E&gt;(E [] Numbers)\n    {\n        foreach (E element in Numbers)\n        {\n            Console.WriteLine(element);\n        }\n    }\n</code></pre>\n"}, {'answer_id': 2021617, 'author': 'iChaib', 'author_id': 185854, 'author_profile': 'https://Stackoverflow.com/users/185854', 'pm_score': 2, 'selected': False, 'text': '<ul>\n<li>Attaching  <strong>?</strong> to a Type to make it\nnullable, ex: int? </li>\n<li>"c:\\dir" instead of <strong>@"C:\\dir"</strong></li>\n</ul>\n'}, {'answer_id': 2026781, 'author': 'cllpse', 'author_id': 20946, 'author_profile': 'https://Stackoverflow.com/users/20946', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Easier-on-the-eyes / condensed ORM-mapping using LINQ</strong></p>\n\n<p>Consider this table:</p>\n\n<pre><code>[MessageId] INT,\n[MessageText] NVARCHAR(MAX)\n[MessageDate] DATETIME\n</code></pre>\n\n<p>... And this structure:</p>\n\n<pre><code>struct Message\n{\n    Int32 Id;\n    String Text;\n    DateTime Date;\n}\n</code></pre>\n\n<p><br />\n<br />\nInstead of doing something along the lines of:</p>\n\n<pre><code>List&lt;Message&gt; messages = new List&lt;Message&gt;();\n\nforeach (row in DataTable.Rows)\n{\n    var message = new Message\n    {\n        Id = Convert.ToInt32(row["MessageId"]),\n        Text = Convert.ToString(row["MessageText"]),\n        Date = Convert.ToDateTime(row["MessageDate"])\n    };\n\n    messages.Add(message);\n}\n</code></pre>\n\n<p>You can use LINQ and do the same thing with fewer lines of code, and in my opinion; more style. Like so:</p>\n\n<pre><code>var messages = DataTable.AsEnumerable().Select(r =&gt; new Message\n{\n    Id = Convert.ToInt32(r["MessageId"]),\n    Text = Convert.ToString(r["MessageText"]),\n    Date = Convert.ToDateTime(r["MessageDate"])\n}).ToList();\n</code></pre>\n\n<p>This approach can be nested, just like loops can.</p>\n'}, {'answer_id': 2031994, 'author': 't0mm13b', 'author_id': 206367, 'author_profile': 'https://Stackoverflow.com/users/206367', 'pm_score': 3, 'selected': False, 'text': '<p>Having read through all 9 pages of this I felt I had to point out a little unknown feature...</p>\n\n<p>This was held true for .NET 1.1, using compression/decompression on gzipped files, one had to either:</p>\n\n<ul>\n<li>Download <a href="http://www.icsharpcode.net/OpenSource/SharpZipLib/" rel="nofollow noreferrer">ICSharpCode.ZipLib</a></li>\n<li>Or, reference the Java library into your project and use the Java\'s in-built library to take advantage of the GZip\'s compression/decompression methods.</li>\n</ul>\n\n<p>It is underused, that I did not know about, (still use ICSharpCode.ZipLib still, even with .NET 2/3.5) was that it was incorporated into the standard BCL version 2 upwards, in the System.IO.Compression namespace... see the MSDN page "<a href="http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream(VS.80).aspx" rel="nofollow noreferrer">GZipStream Class</a>".</p>\n'}, {'answer_id': 2035708, 'author': 'Jamie Keeling', 'author_id': 218159, 'author_profile': 'https://Stackoverflow.com/users/218159', 'pm_score': 3, 'selected': False, 'text': '<p>I find the use of the conditional break function in Visual Studio very useful. I like the way it allows me to set the value to something that, for example can only be met in rare occasions and from there I can examine the code further.</p>\n'}, {'answer_id': 2055618, 'author': 'David Stocking', 'author_id': 249602, 'author_profile': 'https://Stackoverflow.com/users/249602', 'pm_score': 2, 'selected': False, 'text': '<p>Don\'t know if this is a secret per se but I loved the added Enumerable (adds to IEnumerable) class in System.Linq.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable_members.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.linq.enumerable_members.aspx</a></p>\n\n<p>While the yield keyword is already listed. Iterator blocks are freaking amazing. I used them to build Lists that would be tested to see if they were co-prime. It basically allows you to go though a function that returns values one by one and stop any time.</p>\n\n<p>Oh, I almost forgot the best class in the world when you can\'t optimize it any more. The BackgroundWorker!!!!</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx</a></p>\n'}, {'answer_id': 2132689, 'author': 'Mohammad Tayseer', 'author_id': 85245, 'author_profile': 'https://Stackoverflow.com/users/85245', 'pm_score': 5, 'selected': False, 'text': "<p>I didn't find anyone who is using string.Join to join strings using a separator. Everyone keeps writing the same ugly for-loop</p>\n\n<pre><code>var sb = new StringBuilder();\nvar count = list.Count();\nfor(int i = 0; i &lt; count; i++)\n{\n  if (sb.Length &gt; 0) sb.Append(seperator);\n  sb.Append(list[i]);\n}\n\nreturn sb.ToString();\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>return string.Join(separator, list.ToArray());\n</code></pre>\n"}, {'answer_id': 2141921, 'author': 'devforall', 'author_id': 43838, 'author_profile': 'https://Stackoverflow.com/users/43838', 'pm_score': 2, 'selected': False, 'text': '<p>Another way of geting IEnumerable through yield without explicity creating an IEnumerable object</p>\n\n<pre><code>public IEnumerable&lt;Request&gt; SomeMethod(IEnumerable&lt;Request&gt; requests)\n{\n    foreach (Request request in requests)\n       yield return DoSomthing(request);\n}\n</code></pre>\n'}, {'answer_id': 2188117, 'author': 'murki', 'author_id': 5953, 'author_profile': 'https://Stackoverflow.com/users/5953', 'pm_score': 2, 'selected': False, 'text': '<p>I just want to mention (because of the OP metioning where T : struct) that one of the C# compiler gotchas is that </p>\n\n<pre><code>where T : Enum\n</code></pre>\n\n<p>will NOT compile. It throws the error "Constraint cannot be special class \'System.Enum\'".</p>\n'}, {'answer_id': 2231697, 'author': 'Max Toro', 'author_id': 39923, 'author_profile': 'https://Stackoverflow.com/users/39923', 'pm_score': 2, 'selected': False, 'text': '<p>Collection Initializer inside Object Initializer:</p>\n\n<pre><code>MailMessage mail = new MailMessage {\n   To = { new MailAddress("a@example.com"), new MailAddress("b@example.com") },\n   Subject = "Password Recovery"\n};\n</code></pre>\n\n<p>You can initialize a whole tree in a single expression.</p>\n'}, {'answer_id': 2243846, 'author': 'Mubashar', 'author_id': 806076, 'author_profile': 'https://Stackoverflow.com/users/806076', 'pm_score': 2, 'selected': False, 'text': '<p>I am bit late in this conversation and I would like to contribute the following. It may be a new thing for some developers.</p>\n\n<pre><code>public class User\n{\n    public long UserId { get; set; }\n    public String Name { get; set; }\n    public String Password { get; set; }\n    public String Email { get; set; }\n}\n</code></pre>\n\n<p>The usual way to declare and initialize it is with a constructor or like following.</p>\n\n<pre><code>User user = new User();\nuser.UserId = 1;\nuser.Name = "myname";\netc\n</code></pre>\n\n<p>But I learned following way to initialize it. I know Visual Basic developers will love it because it\'s like with operator available only in VB.NET and not in C# that is as follows.</p>\n\n<pre><code>User user = new User()\n{\n    UserId = 1,\n    Name = "myname",\n    Email = "myemail@domain.com",\n    Password = "mypassword"\n};\n</code></pre>\n'}, {'answer_id': 2262310, 'author': 'A1exandr Belan', 'author_id': 87713, 'author_profile': 'https://Stackoverflow.com/users/87713', 'pm_score': 4, 'selected': False, 'text': '<p>You can store colors in Enum.</p>\n\n<pre><code>public enum MyEnumColors : uint\n{\n    Normal          = 0xFF9F9F9F,\n    Active          = 0xFF8EA98A,\n    Error           = 0xFFFF0000\n}\n</code></pre>\n'}, {'answer_id': 2271941, 'author': 'Ruben Bartelink', 'author_id': 11635, 'author_profile': 'https://Stackoverflow.com/users/11635', 'pm_score': 2, 'selected': False, 'text': '<p>This <a href="http://elegantcode.com/2010/01/28/calling-non-public-methods/" rel="nofollow noreferrer">trick for calling private methods using Delegate.CreateDelegate</a> is extremely neat. </p>\n\n<pre><code>var subject = new Subject();\nvar doSomething = (Func&lt;String, String&gt;)\n    Delegate.CreateDelegate(typeof(Func&lt;String, String&gt;), subject, "DoSomething");\nConsole.WriteLine(doSomething("Hello Freggles"));\n</code></pre>\n\n<p><a href="https://stackoverflow.com/questions/1043899/non-code-generated-forwarding-shim-for-testing-private-methods/1804696#1804696">Here\'s a context where it\'s useful</a></p>\n'}, {'answer_id': 2293955, 'author': 'rerun', 'author_id': 149458, 'author_profile': 'https://Stackoverflow.com/users/149458', 'pm_score': 0, 'selected': False, 'text': '<p>I don\'t know if this is a hidden feature (""). Any string function.</p>\n'}, {'answer_id': 2359623, 'author': 'Grokys', 'author_id': 6448, 'author_profile': 'https://Stackoverflow.com/users/6448', 'pm_score': 3, 'selected': False, 'text': '<p>To test if an IEnumerable<code>&lt;T&gt;</code> is empty with LINQ, use:</p>\n\n<blockquote>\n  <p>IEnumerable<code>&lt;T&gt;</code>.Any();</p>\n</blockquote>\n\n<ul>\n<li>At first, I was using (IEnumerable<code>&lt;T&gt;</code>.Count() != 0)...\n\n<ul>\n<li>Which unnecessarily causes all items in the IEnumerable<code>&lt;T&gt;</code> to be enumerated.</li>\n</ul></li>\n<li>As an improvement to this, I went on to use (IEnumerable<code>&lt;T&gt;</code>.FirstOrDefault() == null)...\n\n<ul>\n<li>Which is better...</li>\n</ul></li>\n<li>But IEnumerable<code>&lt;T&gt;</code>.Any() is the most succinct and performs the best.</li>\n</ul>\n'}, {'answer_id': 2361060, 'author': 'Dax70', 'author_id': 182227, 'author_profile': 'https://Stackoverflow.com/users/182227', 'pm_score': 2, 'selected': False, 'text': '<p>Most of the <a href="http://en.wikipedia.org/wiki/Platform_Invocation_Services" rel="nofollow noreferrer">P/Invoke</a> stuff is a bit strange.</p>\n\n<p>Example of attributes:</p>\n\n<pre><code>[DllImport ("gdi32.dll")] \n[return : MarshalAs(UnmanagedType.I4)]\n[StructLayout(LayoutKind.Sequential)]\n</code></pre>\n'}, {'answer_id': 2405367, 'author': 'Anthony Mastrean', 'author_id': 3619, 'author_profile': 'https://Stackoverflow.com/users/3619', 'pm_score': 3, 'selected': False, 'text': "<p><strong>Empty blocks with braces are allowed.</strong></p>\n\n<p>You can write code like this</p>\n\n<pre><code>{\n    service.DoTonsOfWork(args);\n}\n</code></pre>\n\n<p>It's helpful when you want to try something without a <code>using</code> or <code>try... finally</code> that you've already written.</p>\n\n<pre><code>//using(var scope = new TransactionScope)\n{\n    service.DoTonsOfWork(args);\n}\n</code></pre>\n"}, {'answer_id': 2425985, 'author': 'Silviu', 'author_id': 260847, 'author_profile': 'https://Stackoverflow.com/users/260847', 'pm_score': 2, 'selected': False, 'text': '<p>One of the most useful features Visual Studio has is "Make object id". It generates an id and "attaches" to the object so wherever you look at the object you will also see the id (regardless of the thread).</p>\n\n<p>While debugging right click on the variable tooltip and there you have it.\nIt also works on watched/autos/locals variables.</p>\n'}, {'answer_id': 2455744, 'author': 'Edison Chuang', 'author_id': 83946, 'author_profile': 'https://Stackoverflow.com/users/83946', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Using "~" operator with FlagAttribute and enum</strong><br>\nSometime we would use Flag attribute with enum to perform bitwise manipulation on the enumeration.</p>\n\n<pre><code> [Flags]\n public enum Colors\n {\n    None  = 0,\n    Red   = 1,\n    Blue  = 2,\n    White = 4,\n    Black = 8,\n    Green = 16,\n    All   = 31 //It seems pretty bad...\n }\n</code></pre>\n\n<p>Notice that, the value of option "All" which in enum is quite strange.<br>\nInstead of that we can use "~" operator with flagged enum.</p>\n\n<pre><code> [Flags]\n public enum Colors\n {\n    None  = 0,\n    Red   = 1,\n    Blue  = 2,\n    White = 4,\n    Black = 8,\n    Green = 16,\n    All   = ~0 //much better now. that mean 0xffffffff in default.\n }\n</code></pre>\n'}, {'answer_id': 2484117, 'author': 'user287107', 'author_id': 287107, 'author_profile': 'https://Stackoverflow.com/users/287107', 'pm_score': 3, 'selected': False, 'text': "<p>With LINQ it's possible to create new functions based on parameters.\nThat's very nice if you have a tiny function which is exectued very often, but the parameters need some time to calculate.</p>\n\n<pre><code>    public Func&lt;int&gt; RandomGenerator\n    {\n        get\n        {\n            var r = new Random();\n            return () =&gt; { return r.Next(); };\n        }\n    }\n\n    void SomeFunction()\n    {\n        var result1 = RandomGenerator();\n\n        var x = RandomGenerator;\n        var result2 = x();\n    }\n</code></pre>\n"}, {'answer_id': 2495330, 'author': 'John K', 'author_id': 179972, 'author_profile': 'https://Stackoverflow.com/users/179972', 'pm_score': 5, 'selected': False, 'text': '<h1>Arbitrary nested scopes { }</h1>\n\n<p><br />  </p>\n\n<h2>1. For finer scoping behaviour</h2>\n\n<p><strong>{</strong> anywhere inside members <strong>}</strong>, <strong>{</strong> using only braces <strong>}</strong>, <strong>{</strong> with no control statement <strong>}</strong>.</p>\n\n<pre><code>void MyWritingMethod() {\n\n    int sameAge = 35;\n\n\n    { // scope some work\n        string name = "Joe";\n        Log.Write(name + sameAge.ToString());\n    }\n\n\n    { // scope some other work\n        string name = "Susan";\n        Log.Write(name + sameAge.ToString());\n    }\n\n    // I\'ll never mix up Joe and Susan again\n}\n</code></pre>\n\n<p>Inside large, confusing or archaic members (not that they should ever exist, however,) it helps me prevent against using wrong variable names. Scope stuff to finer levels. \n<br />\n<br /></p>\n\n<h2>2. For code beautification or visual semantics</h2>\n\n<p>For example, this XML writing code follows the indentation level of the actual generated XML (i.e. Visual Studio will indent the scoping braces accordingly)</p>\n\n<pre><code>XmlWriter xw = new XmlWriter(..);\n\n//&lt;root&gt;\nxw.WriteStartElement("root");\n{\n    //&lt;game&gt;\n    xw.WriteStartElement("game");\n    {\n        //&lt;score&gt;#&lt;/score&gt;\n        for (int i = 0; i &lt; scores.Length; ++i) // multiple scores\n            xw.WriteElementString("score", scores[i].ToString());\n\n    }\n    //&lt;/game&gt;\n    xw.WriteEndElement();\n}\n//&lt;/root&gt;\nxw.WriteEndElement();\n</code></pre>\n\n<h2>3. Mimic a \'with\' statement</h2>\n\n<p>(Also another use to keep temp work out of the main scope)<br>\nProvided by <a href="https://stackoverflow.com/users/46187/">Patrik</a>:  sometimes used to mimic the VB "with-statement" in C#.</p>\n\n<pre><code>var somePerson = this.GetPerson();  // whatever \n{ \n    var p = somePerson; \n    p.FirstName = "John"; \n    p.LastName = "Doe"; \n    //... \n    p.City = "Gotham"; \n} \n</code></pre>\n\n<p>For the discerning programmer.</p>\n'}, {'answer_id': 2531350, 'author': 'Dariusz', 'author_id': 59528, 'author_profile': 'https://Stackoverflow.com/users/59528', 'pm_score': 3, 'selected': False, 'text': '<p>You can change rounding scheme using:</p>\n\n<pre><code>var value = -0.5;\nvar value2 = 0.5;\nvar value3 = 1.4;\n\nConsole.WriteLine( Math.Round(value, MidpointRounding.AwayFromZero) ); //out: -1\nConsole.WriteLine(Math.Round(value2, MidpointRounding.AwayFromZero)); //out: 1\nConsole.WriteLine(Math.Round(value3, MidpointRounding.ToEven)); //out: 1\n</code></pre>\n'}, {'answer_id': 2576855, 'author': 'Joshua Rodgers', 'author_id': 308118, 'author_profile': 'https://Stackoverflow.com/users/308118', 'pm_score': 2, 'selected': False, 'text': '<p>This relates to static constructors.  This is a method for performing static destruction (i.e. cleaning up resources when the program quits).</p>\n\n<p>First off the class:</p>\n\n<pre><code>class StaticDestructor\n{\n    /// &lt;summary&gt;\n    /// The delegate that is invoked when the destructor is called.\n    /// &lt;/summary&gt;\n    public delegate void Handler();\n    private Handler doDestroy;\n\n    /// &lt;summary&gt;\n    /// Creates a new static destructor with the specified delegate to handle the destruction.\n    /// &lt;/summary&gt;\n    /// &lt;param name="method"&gt;The delegate that will handle destruction.&lt;/param&gt;\n    public StaticDestructor(Handler method)\n    {\n        doDestroy = method;\n    }\n\n    ~StaticDestructor()\n    {\n        doDestroy();\n    }\n}\n</code></pre>\n\n<p>Then as a member of the class you wish to have a "static destructor" do:</p>\n\n<pre><code>private static readonly StaticDestructor destructor = new StaticDestructor\n(\n    delegate()\n    {\n        //Cleanup here\n    }\n);\n</code></pre>\n\n<p>This will now be called when final garbage collection occurs.  This is useful if you absolutely need to free up certain resources.</p>\n\n<p>A quick and dirty program exhibiting this behavior:</p>\n\n<pre><code>using System;\n\nnamespace TestStaticDestructor\n{\n    class StaticDestructor\n    {\n        public delegate void Handler();\n        private Handler doDestroy;\n\n        public StaticDestructor(Handler method)\n        {\n            doDestroy = method;\n        }\n\n        ~StaticDestructor()\n        {\n            doDestroy();\n        }\n    }\n\n    class SomeClass\n    {\n        static SomeClass()\n        {\n            Console.WriteLine("Statically constructed!");\n        }\n\n        static readonly StaticDestructor destructor = new StaticDestructor(\n            delegate()\n            {\n                Console.WriteLine("Statically destructed!");\n            }\n        );\n    }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            SomeClass someClass = new SomeClass();\n            someClass = null;\n            System.Threading.Thread.Sleep(1000);\n        }\n    }\n}\n</code></pre>\n\n<p>When the program exits, the "static destructor" is called.</p>\n'}, {'answer_id': 2578029, 'author': 'Anemoia', 'author_id': 162694, 'author_profile': 'https://Stackoverflow.com/users/162694', 'pm_score': 3, 'selected': False, 'text': '<p>Nullable.GetValueOrDefault  ? </p>\n'}, {'answer_id': 2578334, 'author': 'Nakul Chaudhary', 'author_id': 34588, 'author_profile': 'https://Stackoverflow.com/users/34588', 'pm_score': 3, 'selected': False, 'text': '<p>I like </p>\n\n<pre><code>#if DEBUG\n           //Code run in debugging mode\n\n#else\n           //Code run in release mode\n\n#endif\n</code></pre>\n'}, {'answer_id': 2602813, 'author': 'k25', 'author_id': 312219, 'author_profile': 'https://Stackoverflow.com/users/312219', 'pm_score': 2, 'selected': False, 'text': '<p>With reference to the post w/ perma link "<a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/2495330#2495330">Hidden Features of C#?</a>", there is another way to accomplish the same - indentation / line breaks. Check this out..</p>\n\n<pre><code>XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();\nxmlWriterSettings.NewLineOnAttributes = true;\nxmlWriterSettings.Indent = true;\n\n\nXmlWriter xml = XmlWriter.Create(@"C:\\file.xml", xmlWriterSettings);\n\n// Start writing the data using xml.WriteStartElement(), xml.WriteElementString(...), xml.WriteEndElement() etc\n</code></pre>\n\n<p>I am not sure whether this is an unknown feature though!</p>\n'}, {'answer_id': 2684383, 'author': 'ntziolis', 'author_id': 268742, 'author_profile': 'https://Stackoverflow.com/users/268742', 'pm_score': 4, 'selected': False, 'text': '<p>What about <strong>IObservable</strong>?</p>\n\n<p>Pretty much everybody knows <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" rel="nofollow noreferrer"><strong>IEnumerable</strong></a> but their mathematical dual seems to be unknown <a href="http://msdn.microsoft.com/en-us/library/dd990377.aspx" rel="nofollow noreferrer"><strong>IObservable</strong></a>. Maybe because its new in .NET 4.</p>\n\n<p>What it does is instead of pulling the information (like an enumerable) it pushes information to the subscriber(s) of the observerable.</p>\n\n<p>Together with the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx" rel="nofollow noreferrer"><strong>Rx extensions</strong></a> it will change how we deal with events. Just to illustrate how powerful it is check a very short example <a href="http://channel9.msdn.com/posts/J.Van.Gogh/Writing-your-first-Rx-Application/" rel="nofollow noreferrer"><strong>here</strong></a>.</p>\n'}, {'answer_id': 2689007, 'author': 'Jehof', 'author_id': 83039, 'author_profile': 'https://Stackoverflow.com/users/83039', 'pm_score': 4, 'selected': False, 'text': '<p>When a class implements <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged%28v=VS.80%29.aspx" rel="nofollow noreferrer">INotifyPropertyChanged</a> and you want to inform the binding system (WPF, Silverlight, etc.) that multiple bound properties of an object (ViewModel) have changed you can raise the PropertyChanged-Event with <strong>null</strong> or <strong>String.Empty</strong>.</p>\n\n<p>This is documented in MSDN, but code examples and articles often don´t explain this possibility. I found it very useful.</p>\n\n<pre><code>public class BoundObject : INotifyPropertyChanged {\n\n    private int _value;\n    private string _text;\n\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    public int Value {\n        get {\n            return _value;\n        }\n        set {\n            if (_value != value) {\n                _value = value;\n                OnPropertyChanged("Value");\n            }\n        }\n    }\n\n    public string Text {\n        get {\n            return _text;\n        }\n        set {\n            if (_text != value) {\n                _text = value;\n                OnPropertyChanged("Text");\n            }\n        }\n    }\n\n    public void Init(){\n        _text = "InitialValue";\n        _value = 1;\n        OnPropertyChanged(string.Empty);\n    }\n\n    public void Reset() {\n        _text = "DefaultValue";\n        _value = 0;\n        OnPropertyChanged(string.Empty);\n    }\n\n    private void OnPropertyChanged(string propertyName) {\n        PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);\n\n        if (PropertyChanged != null) {\n            PropertyChanged(this, e);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 2753564, 'author': 'Navid Farhadi', 'author_id': 184756, 'author_profile': 'https://Stackoverflow.com/users/184756', 'pm_score': 3, 'selected': False, 'text': '<p>This means T must have a public parameterless constructor :</p>\n\n<pre><code> class MyClass&lt;T&gt; where T : new()\n {\n\n }\n</code></pre>\n'}, {'answer_id': 2836741, 'author': 'Pretzel', 'author_id': 21244, 'author_profile': 'https://Stackoverflow.com/users/21244', 'pm_score': 3, 'selected': False, 'text': '<p>I was reading thru the book "Pro ASP.NET MVC Framework" (APress) and observed something the author was doing with a Dictionary object that was foreign to me. </p>\n\n<p>He added a new Key/Value Pair without using the Add() method. He then overwrote that same Key/Value pair without having to check if that key already existed. For example:</p>\n\n<pre><code>Dictionary&lt;string, int&gt; nameAgeDict = new Dictionary&lt;string, int&gt;();\nnameAgeDict["Joe"] = 34;      // no error. will just auto-add key/value\nnameAgeDict["Joe"] = 41;      // no error. key/value just get overwritten\nnameAgeDict.Add("Joe", 30);   // ERROR! key already exists\n</code></pre>\n\n<p>There are many cases where I don\'t need to check if my Dictionary already has a key or not and I just want to add the respective key/value pair (overwriting the existing key/value pair, if necessary.) Prior to this discovery, I would always have to check to see if the key already existed before adding it.</p>\n'}, {'answer_id': 2843263, 'author': 'Razor', 'author_id': 17211, 'author_profile': 'https://Stackoverflow.com/users/17211', 'pm_score': 1, 'selected': False, 'text': '<p>Separate static fields depending on the generic type of the surrounding class.</p>\n\n<pre><code>    public class StaticConstrucEx2Outer&lt;T&gt; {\n\n // Will hold a different value depending on the specicified generic type\n public T SomeProperty { get; set; }\n\n static StaticConstrucEx2Outer() {\n  Console.WriteLine("StaticConstrucEx2Outer " + typeof(T).Name);\n }\n\n public class StaticConstrucEx2Inner&lt;U, V&gt; {\n\n  static StaticConstrucEx2Inner() {\n\n   Console.WriteLine("Outer &lt;{0}&gt; : Inner &lt;{1}&gt;&lt;{2}&gt;",\n    typeof(T).Name,\n    typeof(U).Name,\n    typeof(V).Name);\n  }\n\n  public static void FooBar() {}\n }\n\n public class SCInner {\n\n  static SCInner() {\n   Console.WriteLine("SCInner init &lt;{0}&gt;", typeof(T).Name);\n  }\n\n  public static void FooBar() {}\n }\n}\n\n\nStaticConstrucEx2Outer&lt;int&gt;.StaticConstrucEx2Inner&lt;string, DateTime&gt;.FooBar();\nStaticConstrucEx2Outer&lt;int&gt;.SCInner.FooBar();\n\nStaticConstrucEx2Outer&lt;string&gt;.StaticConstrucEx2Inner&lt;string, DateTime&gt;.FooBar();\nStaticConstrucEx2Outer&lt;string&gt;.SCInner.FooBar();\n\nStaticConstrucEx2Outer&lt;string&gt;.StaticConstrucEx2Inner&lt;string, Int16&gt;.FooBar();\nStaticConstrucEx2Outer&lt;string&gt;.SCInner.FooBar();\n\nStaticConstrucEx2Outer&lt;string&gt;.StaticConstrucEx2Inner&lt;string, UInt32&gt;.FooBar();\n\nStaticConstrucEx2Outer&lt;long&gt;.StaticConstrucEx2Inner&lt;string, UInt32&gt;.FooBar();\n</code></pre>\n\n<p>Will produce the following output</p>\n\n<pre><code>Outer &lt;Int32&gt; : Inner &lt;String&gt;&lt;DateTime&gt;\nSCInner init &lt;Int32&gt;\n\nOuter &lt;String&gt; : Inner &lt;String&gt;&lt;DateTime&gt;\nSCInner init &lt;String&gt;\n\nOuter &lt;String&gt; : Inner &lt;String&gt;&lt;Int16&gt;\n\nOuter &lt;String&gt; : Inner &lt;String&gt;&lt;UInt32&gt;\n\nOuter &lt;Int64&gt; : Inner &lt;String&gt;&lt;UInt32&gt;\n</code></pre>\n'}, {'answer_id': 2905415, 'author': 'Thomas Levesque', 'author_id': 98713, 'author_profile': 'https://Stackoverflow.com/users/98713', 'pm_score': 4, 'selected': False, 'text': "<p>OK, it may seem obvious, but I want to mention the <code>Object.Equals</code> method (the static one, with two arguments).</p>\n\n<p>I'm pretty sure many people don't even know about it, or forget it's there, yet it can really help in some cases. For instance, when you want to compare two objects for equality, not knowing if they're null. How many times did you write something like that :</p>\n\n<pre><code>if ((x == y) || ((x != null &amp;&amp; y != null) &amp;&amp; x.Equals(y)))\n{\n    ...\n}\n</code></pre>\n\n<p>When you can just write :</p>\n\n<pre><code>if (Object.Equals(x, y))\n{\n    ...\n}\n</code></pre>\n\n<p>(<code>Object.Equals</code> is actually implemented exactly like in the first code sample)</p>\n"}, {'answer_id': 2918238, 'author': 'Kim Tranjan', 'author_id': 340381, 'author_profile': 'https://Stackoverflow.com/users/340381', 'pm_score': 5, 'selected': False, 'text': '<p>Width in <code>string.Format()</code></p>\n\n<pre><code>Console.WriteLine("Product: {0,-7} Price: {1,5}", product1, price1);\nConsole.WriteLine("Product: {0,-7} Price: {1,5}", product2, price2);\n</code></pre>\n\n<p>produces</p>\n\n<p><img src="https://i.imgur.com/e0hg3.png" alt="alt text"></p>\n\n<p>from  <a href="http://blog.prabir.me/post/Hidden-C-feature-stringFormat-Width.aspx" rel="nofollow noreferrer">Prabir\'s Blog | Hidden C# feature</a> </p>\n'}, {'answer_id': 3006868, 'author': 'Centro', 'author_id': 362287, 'author_profile': 'https://Stackoverflow.com/users/362287', 'pm_score': 2, 'selected': False, 'text': '<p>Lately I learned about the String.Join method. It is really useful when building strings like columns to select by a query.</p>\n'}, {'answer_id': 3031174, 'author': 'Buildstarted', 'author_id': 365526, 'author_profile': 'https://Stackoverflow.com/users/365526', 'pm_score': 5, 'selected': False, 'text': '<p>typedefs</p>\n\n<p>Someone posted that they miss typedefs but you can do it like this</p>\n\n<pre><code>using ListOfDictionary = System.Collections.Generic.List&lt;System.Collections.Generic.Dictionary&lt;string, string&gt;&gt;;\n</code></pre>\n\n<p>and declare it as</p>\n\n<pre><code>ListOfDictionary list = new ListOfDictionary();\n</code></pre>\n'}, {'answer_id': 3090178, 'author': 'jcruz', 'author_id': 358007, 'author_profile': 'https://Stackoverflow.com/users/358007', 'pm_score': 6, 'selected': False, 'text': "<p>Here is a new method of the string class in C# 4.0:</p>\n\n<pre><code>String.IsNullOrWhiteSpace(String value)\n</code></pre>\n\n<p>It's about time.</p>\n"}, {'answer_id': 3093285, 'author': 'Steve Dunn', 'author_id': 28901, 'author_profile': 'https://Stackoverflow.com/users/28901', 'pm_score': 4, 'selected': False, 'text': "<p>Not really hidden, but useful.  When you've got an <code>enum</code> with <code>flags</code>, you can use shift-left to make things clearer.  e.g.</p>\n\n<pre><code>[Flags]\npublic enum ErrorTypes {\n    None              = 0,\n    MissingPassword   = 1 &lt;&lt; 0,\n    MissingUsername   = 1 &lt;&lt; 1,\n    PasswordIncorrect = 1 &lt;&lt; 2 \n}\n</code></pre>\n"}, {'answer_id': 3094954, 'author': 'Bill Barry', 'author_id': 108993, 'author_profile': 'https://Stackoverflow.com/users/108993', 'pm_score': 4, 'selected': False, 'text': "<p>Another note on event handlers: you can simply create a raise extension method like so:</p>\n\n<pre><code>public static class EventExtensions {\n    public static void Raise&lt;T&gt;(this EventHandler&lt;T&gt; @event, \n                                object sender, T args) where T : EventArgs {\n        if(@event!= null) {\n            @event(sender, args);\n        }\n    }\n}\n</code></pre>\n\n<p>Then you can use it to raise events:</p>\n\n<pre><code>public class MyImportantThing {\n    public event EventHandler&lt;MyImportantEventEventArgs&gt; SomethingHappens;\n    ...\n    public void Bleh() {\n        SomethingHappens.Raise(this, new MyImportantEventEventArgs { X=true });\n    }\n}\n</code></pre>\n\n<p>This method has the added advantage of enforcing a coding standard (using <code>EventHandler&lt;&gt;</code>).</p>\n\n<p>There isn't a point in writing the same exact function over and over and over again. Perhaps the next version of C# will finally have an <code>InlineAttribute</code> that can be placed on the extension method and will cause the compiler to inline the method definition (which would make this way nearly standard, and the fastest).</p>\n\n<p>edit: removed temp variable inside extension method based on comments</p>\n"}, {'answer_id': 3096408, 'author': 'Steve Dunn', 'author_id': 28901, 'author_profile': 'https://Stackoverflow.com/users/28901', 'pm_score': 6, 'selected': False, 'text': "<p>When debugging, you can type <code>$exception</code> in the Watch\\QuickWatch\\Immediate window and get all the info on the exception of the current frame.  This is very useful if you've got 1st chance exceptions turned on!</p>\n"}, {'answer_id': 3096656, 'author': 'STW', 'author_id': 60724, 'author_profile': 'https://Stackoverflow.com/users/60724', 'pm_score': 2, 'selected': False, 'text': '<p>I don\'t condone it, but I was surprised that <a href="http://msdn.microsoft.com/en-us/library/13940fs2(VS.100).aspx" rel="nofollow noreferrer">goto</a> is still around <em>ducks incoming projectiles</em></p>\n'}, {'answer_id': 3138039, 'author': 'Keith Bluestone', 'author_id': 378081, 'author_profile': 'https://Stackoverflow.com/users/378081', 'pm_score': 5, 'selected': False, 'text': '<p><strong>RealProxy lets you create your own proxies for existing types.</strong></p>\n\n<p>This is super-advanced and I haven\'t seen anyone else use it -- which may mean that it\'s also really not that useful for most folks -- but it\'s one of those things that\'s good to know.   </p>\n\n<p>Basically, the .NET <strong>RealProxy</strong> class lets you create what is called a <em>transparent proxy</em> to another type.  Transparent in this case means that it looks completely like the proxied target object to its client -- but it\'s really not:  it\'s an instance of your class, which is derived from RealProxy.  </p>\n\n<p>This lets you apply powerful and comprehensive interception and "intermediation" services between the client and any methods or properties invoked on the real target object.  Couple this power with the factory pattern (IoC etc), and you can hand back transparent proxies instead of real objects, allowing you to intercept all calls to the real objects and perform actions before and after each method invocation.  In fact, I believe this is the very functionality .NET uses for remoting across app domain, process, and machine boundaries:  .NET intercepts all access, sends serialized info to the remote object, receives the response, and returns it to your code.</p>\n\n<p>Maybe an example will make it clear how this can be useful: I created a reference service stack for my last job as enterprise architect which specified the standard internal composition (the "stack") of any new WCF services across the division.  The model mandated that the data access layer for (say) the Foo service implement <code>IDAL&lt;Foo&gt;:</code>  create a Foo, read a Foo, update a Foo, delete a Foo.  Service developers used supplied common code (from me) that would locate and load the required DAL for a service: </p>\n\n<pre><code>IDAL&lt;T&gt; GetDAL&lt;T&gt;(); // retrieve data access layer for entity T\n</code></pre>\n\n<p>Data access strategies in that company had often been, well, performance-challenged.  As an architect, I couldn\'t watch over every service developer to make sure that he/she wrote a performant data access layer.  But what I could do within the <em>GetDAL</em> factory pattern was create <strong>a transparent proxy</strong> to the requested DAL (once the common service model code located the DLL and loaded it), and use high-performance timing APIs to profile all calls to any method of the DAL.  Ranking laggards then is just a matter of sorting DAL call timings by descending total time.  The advantage to this over development profiling (e.g. in the IDE) is that it can be done in the production environment as well, to ensure SLAs.   </p>\n\n<p>Here is an example of test code I wrote for the "entity profiler," which was common code to create a profiling proxy for any type with a single line:</p>\n\n<pre><code>[Test, Category("ProfileEntity")]\npublic void MyTest()\n{\n    // this is the object that we want profiled.\n    // we would normally pass this around and call\n    // methods on this instance.\n    DALToBeProfiled dal = new DALToBeProfiled();\n\n    // To profile, instead we obtain our proxy\n    // and pass it around instead.\n    DALToBeProfiled dalProxy = (DALToBeProfiled)EntityProfiler.Instance(dal);\n\n    // or...\n    DALToBeProfiled dalProxy2 = EntityProfiler&lt;DALToBeProfiled&gt;.Instance(dal);\n\n    // Now use proxy wherever we would have used the original...\n    // All methods\' timings are automatically recorded\n    // with a high-resolution timer\n    DoStuffToThisObject(dalProxy);\n\n    // Output profiling results\n    ProfileManager.Instance.ToConsole();\n}\n</code></pre>\n\n<p>Again, this lets you intercept all methods and properties called by the client on the target object!  In your <em>RealProxy-derived</em> class, you have to override <strong>Invoke:</strong></p>\n\n<pre><code>[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n[SecurityPermission(SecurityAction.LinkDemand, \n    Flags = SecurityPermissionFlag.Infrastructure)] // per FxCop\npublic override IMessage Invoke(IMessage msg)\n{\n    IMethodCallMessage msgMethodCall = msg as IMethodCallMessage;\n    Debug.Assert(msgMethodCall != null); // should not be null - research Invoke if this trips. KWB 2009.05.28\n\n    // The MethodCallMessageWrapper\n    // provides read/write access to the method \n    // call arguments. \n    MethodCallMessageWrapper mc =\n        new MethodCallMessageWrapper(msgMethodCall);\n\n    // This is the reflected method base of the called method. \n    MethodInfo mi = (MethodInfo)mc.MethodBase;\n\n    IMessage retval = null;\n\n    // Pass the call to the method and get our return value\n    string profileName = ProfileClassName + "." + mi.Name;\n\n    using (ProfileManager.Start(profileName))\n    {\n        IMessage myReturnMessage =\n           RemotingServices.ExecuteMessage(_target, msgMethodCall);\n\n        retval = myReturnMessage;\n    }\n\n    return retval;\n}\n</code></pre>\n\n<p>Isn\'t it fascinating what .NET can do? The only restriction is that the target type <em>must</em> be derived from <strong><em>MarshalByRefObject</em></strong>.  I hope this is helpful to someone.</p>\n'}, {'answer_id': 3138257, 'author': 'Incognito', 'author_id': 303756, 'author_profile': 'https://Stackoverflow.com/users/303756', 'pm_score': 4, 'selected': False, 'text': '<p>Also useful, but not commonly used : <a href="http://msdn.microsoft.com/en-us/library/ms228973.aspx" rel="nofollow noreferrer">Constrained Execution Regions</a>.</p>\n\n<p>A quote from BCL Team blog :</p>\n\n<blockquote>\n  <p>Constrained execution regions (CER\'s)\n  exist to help a developer write her\n  code to maintain consistency.  The CLR\n  doesn\'t guarantee that the developer\'s\n  code is correct, but the CLR does\n  hoist all of the runtime-induced\n  failure points (ie, async exceptions)\n  to either before the code runs, or\n  after it has completed.  Combined with\n  constraints on what the developer can\n  put in a CER, these are a useful way\n  of making strong guarantees about\n  whether your code will execute.  CER\'s\n  are eagerly prepared, meaning that\n  when we see one, we will eagerly JIT\n  any code found in its\n  statically-discoverable call graph. \n  If the CLR\'s host cares about stack\n  overflow, we\'ll probe for some amount\n  of stack space as well (though perhaps\n  not enough stack space for any\n  arbitrary method*).  We also delay\n  thread aborts until the CER has\n  finished running.</p>\n</blockquote>\n\n<p>It can be useful when making edits to more than one field of a data structure in an atomic fashion. So it helps to have transactions on objects.</p>\n\n<p>Also <a href="http://msdn.microsoft.com/en-us/library/system.runtime.constrainedexecution.criticalfinalizerobject.aspx" rel="nofollow noreferrer">CriticalFinalizerObject</a> seems to be hidden(at least who are not writing unsafe code).\nA CriticalFinalizerObject guarantees that garbage collection will execute the finalizer. Upon allocation, the finalizer and its call graph are prepared in advance. </p>\n'}, {'answer_id': 3146453, 'author': 'Incognito', 'author_id': 303756, 'author_profile': 'https://Stackoverflow.com/users/303756', 'pm_score': 5, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx" rel="nofollow noreferrer">AppDomain.UnhandledException Event</a> is also candidate for being hidden.</p>\n\n<blockquote>\n  <p>This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. If sufficient information about the state of the application is available, other actions may be undertaken — such as saving program data for later recovery. Caution is advised, because program data can become corrupted when exceptions are not handled.</p>\n</blockquote>\n\n<p>We can see, even on this site, a lot of people are wondering why their application is not starting, why it crashed, etc. The <code>AppDomain.UnhandledException</code> event can be very useful for such cases as it provides the possibility at least to log the reason of application failure. </p>\n'}, {'answer_id': 3147945, 'author': 'Dan', 'author_id': 59532, 'author_profile': 'https://Stackoverflow.com/users/59532', 'pm_score': 4, 'selected': False, 'text': '<pre><code>string.Empty\n</code></pre>\n\n<p>I know it\'s not fantastical (ludicrously odd), but I use it all the time instead of "".</p>\n\n<p>And it\'s pretty well hidden until someone tells you it\'s there.</p>\n'}, {'answer_id': 3152079, 'author': 'Incognito', 'author_id': 303756, 'author_profile': 'https://Stackoverflow.com/users/303756', 'pm_score': 4, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/f58wzh21(VS.80).aspx" rel="nofollow noreferrer">fixed</a> statement</p>\n\n<p>This statement prevents the garbage collector from relocating a movable variable. Fixed can also be used to create fixed size buffers.</p>\n\n<blockquote>\n  <p>The fixed statement sets a pointer to a managed variable and "pins" that variable during the execution of statement.</p>\n</blockquote>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/cx9s2sy4(VS.71).aspx" rel="nofollow noreferrer">stackalloc</a></p>\n\n<p>The stackalloc allocates a block of memory on the stack.</p>\n'}, {'answer_id': 3172255, 'author': 'Ozan', 'author_id': 137065, 'author_profile': 'https://Stackoverflow.com/users/137065', 'pm_score': 4, 'selected': False, 'text': '<p>You can put several attributes in one pair of square brackets:</p>\n\n<pre><code>    [OperationContract, ServiceKnownType(typeof(Prism)), ServiceKnownType(typeof(Cuboid))]\n    Shape GetShape();\n</code></pre>\n'}, {'answer_id': 3189640, 'author': 'WedTM', 'author_id': 88770, 'author_profile': 'https://Stackoverflow.com/users/88770', 'pm_score': 3, 'selected': False, 'text': '<p>Not sure if this one has been mentioned or not (11 pages!!)</p>\n\n<p>But the <code>OptionalField</code> attribute for classes is amazing when you are versioning classes/objects that are going to be serialized.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx</a></p>\n'}, {'answer_id': 3189688, 'author': 'AaronLS', 'author_id': 84206, 'author_profile': 'https://Stackoverflow.com/users/84206', 'pm_score': 3, 'selected': False, 'text': '<p>Accessing local variables from anonymous methods allows you to wrap just about any code with new control flow logic, without having to factor out that code into another method.  Local variables declared outside the method are available inside the method such as the <code>endOfLineChar</code> local variable in the example here:</p>\n\n<p><a href="http://aaronls.wordpress.com/2010/02/02/retrying-on-exception-conditionally/" rel="nofollow noreferrer">http://aaronls.wordpress.com/2010/02/02/retrying-on-exception-conditionally/</a></p>\n'}, {'answer_id': 9413174, 'author': 'Laradda', 'author_id': 820089, 'author_profile': 'https://Stackoverflow.com/users/820089', 'pm_score': 2, 'selected': False, 'text': '<p>You can combine the <code>protected</code> and <code>internal</code> accessor to make it public within the same assembly, but protected in a diffrent assembly. This can be used on fields, properties, method and even constants.</p>\n'}]
['https://Stackoverflow.com/questions/9033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31505/']