Tag Archives: C# LINQ

Using _ as an extension method

In C#, as in many other languages, “_” is a valid identifier (as reminded to me by Erik Meijer on a C9 Lecture)

Recently, I used this knowledge to create the following extension method:

    public static class StringExt {

        public static XElement _(this string s,

                            params object[] objs) {

            return new XElement(s, objs);



Why? To enable this coding style





                            from colName in colNames

                            select "th"._(colName)),

                        from e in seq

                        select "tr"._(

                            from f in colFuncs

                            select "td"._( f(e))))))


The above fragment creates an HTML document containing a table, where:

  • IEnumerable<T> seq is a sequence of elements, where each element corresponds to a table row.
  • List<string> colNames is a sequence of column names
  • Linked<Func<T, string>> colFuncs is a sequence of functions, where each function is used to project one sequence element (e) into a column cell.

Without extension methods, this fragment would be written as:

    new XElement("html",

         new XElement("body",

            new XElement("table",

                new XElement("tr",

                    from colName in colNames

                    select new XElement("th", colName)),

                from e in seq

                select new XElement("tr",

                    from f in colFuncs

                    select new XElement("td", f(e))))))


More “noisier”, on my opinion.