segunda-feira, 12 de março de 2012

With statement for C# through extension method

Extension methods are really cool feature. I was missing the VB with statement recently, so I thought it will be cool to implement a really simple extension method to do it. Below are a VB.Net, C#, short C# and C# through With extension method: VB.Net
With dataGridView.Columns["customer"]
    .Width = 200
    .HeaderText = "Customer"
    .HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
End With
C#
dataGridView.Columns["customer"].Width = 200;
dataGridView.Columns["customer"].HeaderText = "Customer";
dataGridView.Columns["customer"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
C# short
var column = dataGridView.Columns["customer"];
column.Width = 200;
column.HeaderText = "Customer";
column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
C# With through extension method
dataGridView.Columns["customer"].With(column => {
    column.Width = 200;
    column.HeaderText = "Customer";
    column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
});

static public class ObjectExtensions
{
    static public void With<T>(this T o, Action<T> action)
    {
        action(o);
    }
}

Nenhum comentário:

Postar um comentário

Feel free to comment on the immoderately.