[1] I too used mixins in C#. Not sure how you'd do it now, but at the time you had to use Castle DynamicProxy and it was...unpleasant. But worth it.
[1] I too used mixins in C#. Not sure how you'd do it now, but at the time you had to use Castle DynamicProxy and it was...unpleasant. But worth it.
namespace Yarp{
public interface IMixinFoo{
}
public static class IMixinFooExt{
public static void DoBar(this IMixinFoo _this){
Console.WriteLine("poo");
}
}
}
namespace Grog{
using Yarp;
class Baz : IMixinFoo{
public static void Main(string[] args){
Grog g = new Grog();
g.DoBar();
g = null;
g.DoBar(); // still works, if DoBar guards against a null-ref exception
}
}
}Extension methods are great for writing anything that chains a lot of method calls together, specifically because they aren't methods on the object. Because it's possible to call an extension method on a null instance, you don't have to inject arbitrary error handling in the middle of your call chain. You can do it at the function site.
That said, there are a number of places where LINQ doesn't chain very well. It's built-in aggregating functions, for one. Average, Sum, Min, etc., don't know how to handle a 0-sized collection. And of course, those functions are notionally not defined for 0-sized collections. But I think a better design is to allow the user to specify a default value in the case of a 0-sized collection, or to just return null (signifying "there is no Average, there is no Sum"), rather than throw an exception. So I have a polyfil of sorts to make similar extensions that play nicer.
Enumerable.Empty<int?>().Average() returns null.
If you have a sequence of integers, you can get the behavior you want by converting the elements to nullable types like this. seq.Average(x => (int?)(x))
Upvotes for an intelligent debate.