Ambiguous call between two C# extension generic methods one where T:class and other where T:struct

EDIT: I’ve now blogged about this in more detail. My original (and I now believe incorrect) thought: generic constraints aren’t taken into account during the overload resolution and type inference phases – they’re only used to validate the result of the overload resolution. EDIT: Okay, after a lot of going round on this, I think … Read more

Possible pitfalls of using this (extension method based) shorthand

We independently came up with the exact same extension method name and implementation: Null-propagating extension method. So we don’t think it’s confusing or an abuse of extension methods. I would write your “multiple levels” example with chaining as follows: propertyValue1 = myObject.IfNotNull(o => o.ObjectProp).IfNotNull(p => p.StringProperty); There’s a now-closed bug on Microsoft Connect that proposed … Read more

Is it appropriate to extend Control to provide consistently safe Invoke/BeginInvoke functionality?

You should create Begin and End extension methods as well. And if you use generics, you can make the call look a little nicer. public static class ControlExtensions { public static void InvokeEx<T>(this T @this, Action<T> action) where T : Control { if (@this.InvokeRequired) { @this.Invoke(action, new object[] { @this }); } else { if … Read more

How do extension methods work?

First, here’s a very quick tutorial on extensions for those learning c#/Unity for anyone googling here: Make a new text file HandyExtensions.cs like this … (note that somewhat confusingly, you can use any name at all for the class which “holds” your extensions – the actual name of the class is never used at all, … Read more

Extension method priority

When the compiler searches for extension methods, it starts with those declared in classes in the same namespace as the calling code, then works outwards until it reaches the global namespace. So if your code is in namespace Foo.Bar.Baz, it will first search Foo.Bar.Baz, then Foo.Bar, then Foo, then the global namespace. It will stop … Read more

FindAll vs Where extension-method

Well, FindAll copies the matching elements to a new list, whereas Where just returns a lazily evaluated sequence – no copying is required. I’d therefore expect Where to be slightly faster than FindAll even when the resulting sequence is fully evaluated – and of course the lazy evaluation strategy of Where means that if you … Read more