ArgumentNullException or NullReferenceException from extension method?

In general, exceptions included, you should treat an extension method as if it were a normal static method. In this case you should throw an ArgumentNullException. Throwing a NullReferenceException here is a bad idea for a few reasons A null reference did not actually occur so seeing one is counterintuitive Throwing a NullReferenceException and causing … Read more

C# naming convention for extension methods for interface

I definitely prefer the name ThingExtensions over IThingExtensions. The reason being that to most programmers an I prefix on a type implies that it is an interface. This is both a very common pattern and part of the .Net Design Guidelines. Adding an I prefix for the extension method case breaks both assumptions and established … Read more

Why doesn’t the Controls collection provide all of the IEnumerable methods?

No, IEnumerable doesn’t have many extension methods on it: IEnumerable<T> does. They are two separate interfaces, although IEnumerable<T> extends IEnumerable. The normal LINQ ways of converting are to use the Cast<T>() and OfType<T>() extension methods which do extend the nongeneric interface: IEnumerable<TextBox> textBoxes = Controls.OfType<TextBox>(); IEnumerable<Control> controls = Controls.Cast<Control>(); The difference between the two is … Read more

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