Coffeehouse Post

Single Post Permalink

View Thread: C# Extension Properties?
  • User profile image
    ktr

    In C# 3 you can create an extension method like this:

    public static class Extensions {
        public static string ToCamelCase(this string s) {
            // perform action
        }
    }


    Well what about properties? They could act as an indexer would, by using brackets around parameters:

    public static class Extensions {
        public static object Cell[this DataTable t, int row, int column] {
            get { return t.Rows[row][column]; }
           
    set { t.Rows[row][column] = value; }
        }
    }
    // ...
    // usage
    dataTable.Cell[0, 2] = "Hello World";

    That example is simple, but I think it could be a powerful concept. Take, for example, Extended Properties in WPF, which can't be added to the class. Extension Properties would allow a simpler syntax. There are also areas in the .NET Framework where a Property would be better suited but a "GetXXX(type param)" method was used because Parameterized Properties don't exist.

    I dunno, it could end up cluttering the language. What do you think?