What is the best or most interesting use of Extension Methods you’ve seen? [closed]

This is one that’s been getting some play from me lately: public static IDisposable Tag(this HtmlHelper html, string tagName) { if (html == null) throw new ArgumentNullException(“html”); Action<string> a = tag => html.Write(String.Format(tag, tagName)); a(“<{0}>”); return new Memento(() => a(“</{0}>”)); } Used like: using (Html.Tag(“ul”)) { this.Model.ForEach(item => using(Html.Tag(“li”)) Html.Write(item)); using(Html.Tag(“li”)) Html.Write(“new”); } Memento is … Read more

How to compare nullable types?

C# supports “lifted” operators, so if the type (bool? in this case) is known at compile you should just be able to use: return x != y; If you need generics, then EqualityComparer<T>.Default is your friend: return !EqualityComparer<T>.Default.Equals(x,y); Note, however, that both of these approaches use the “null == null” approach (contrast to ANSI SQL). … Read more

Pass a lambda expression in place of IComparer or IEqualityComparer or any single-method interface?

I’m not much sure what useful it really is, as I think for most cases in the Base Library expecting an IComparer there’s an overload that expects a Comparison… but just for the record: in .Net 4.5 they’ve added a method to obtain an IComparer from a Comparison: Comparer.Create so you can pass your lambda … Read more

Swift extension example

Creating an extension Add a new swift file with File > New > File… > iOS > Source > Swift File. You can call it what you want. The general naming convention is to call it TypeName+NewFunctionality.swift. Example 1 – Double Double+Conversions.swift import Swift // or Foundation extension Double { func celsiusToFahrenheit() -> Double { … Read more

Why is the ‘this’ keyword required to call an extension method from within the extended class

A couple points: First off, the proposed feature (implicit “this.” on an extension method call) is unnecessary. Extension methods were necessary for LINQ query comprehensions to work the way we wanted; the receiver is always stated in the query so it is not necessary to support implicit this to make LINQ work. Second, the feature … Read more

How to extend C# built-in types, like String?

Since you cannot extend string.Trim(). You could make an Extension method as described here that trims and reduces whitespace. namespace CustomExtensions { //Extension methods must be defined in a static class public static class StringExtension { // This is the extension method. // The first parameter takes the “this” modifier // and specifies the type … Read more