Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set the property name of a C# anonymous type

Is there any way to dynamically set the property name of an anonymous type?

Normally we'd do like this:

var anon = new { name = "Kayes" };

Now I'd like to set the name (or identifier) of the property dynamically, so that this name can come from an XML file or a database.


Thanks guys for your answers. No, my need is definitely not worth all the tedious alternatives. I just wanted to make my code comply with an existing library that was developed by my team lead. But we decided to update the library to support Dictionary types so that it can easily be solved.

Pete, I'm really excited to learn about dynamic types in .NET 4.0

Thanks.

like image 398
Kayes Avatar asked Oct 29 '09 10:10

Kayes


3 Answers

That is not possible because even though the type is anonymous, it is not a dynamic type. It is still a static type, and properties about it must be known at compile time.

You might want to check out the .NET 4.0 "dynamic" keyword for generating true dynamic classes.

like image 52
Pete Avatar answered Oct 15 '22 19:10

Pete


Not without a massive amount of reflection, probably moreso than you're interested in leveraging for what you're doing. Perhaps you should look into instead using a Dictionary, with the key value being the property name.

like image 28
Adam Maras Avatar answered Oct 15 '22 20:10

Adam Maras


As has been mentioned, you can't change the property name; how would you code against it, for example? However, if this is for data-binding, you can do some tricks to bend the display name of properties at runtime - for example ICustomTypeDescriptor/TypeDescriptionProvider (and a custom PropertyDescriptor).

Lots of work; it would need to really be worth it...

Another option is a custom attribute:

using System;
using System.ComponentModel;
using System.Windows.Forms;
class MyDisplayNameAttribute : DisplayNameAttribute {
    public MyDisplayNameAttribute(string value) : base(value) {}
    public override string DisplayName {
        get {
            return @"/// " + base.DisplayNameValue + @" \\\";
        }
    }
}
class Foo {
    [MyDisplayName("blip")]
    public string Bar { get; set; }
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        using (Form form = new Form {
            Controls = {
                new PropertyGrid {
                    Dock = DockStyle.Fill,
                    SelectedObject = new Foo { Bar = "abc"}}
            }
        }) {
            Application.Run(form);
        }
    }
}
like image 28
Marc Gravell Avatar answered Oct 15 '22 19:10

Marc Gravell