Why does this work?

Posted by jsoldi on Stack Overflow See other posts from Stack Overflow or by jsoldi
Published on 2011-01-14T08:47:49Z Indexed on 2011/01/14 8:53 UTC
Read the original article Hit count: 253

Filed under:
|
|

I was googling trying to find a way to call Control.DataBindings.Add without using a string literal but getting the property name from the property itself, which I think would be less error prone, at least for my particular case, since I normally let Visual Studio do the renaming when renaming a property. So my code would look something like DataBindings.Add(GetName(myInstance.myObject)... instead of DataBindings.Add("myObject".... So I found this:

    static string GetName<T>(T item) where T : class
    {
        var properties = typeof(T).GetProperties();
        if (properties.Length != 1) throw new Exception("Length must be 1");
        return properties[0].Name;
    }

That would be called, assuming I have a property called One, this way: string name = GetName(new { this.One }); which would give me "One". I have no clue why does it work and whether is safe to use it or not. I don't even know what that new { this.One } means. And I don't know on which case could it happens that properties.Length is not 1.

By the way, I just tested to rename my property One to Two and Visual Studio turned new { this.One } into new { One = this.Two }, which when used with the GetName function gave me "One", which make the whole thing useless since the name I would be passing to Control.DataBindings.Add would be still "One" after renaming the property.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET