Accessing C# Anonymous Type Objects

How to access property of anonymous type in C#?

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });

Accessing anonymous type variables

If you cannot use static typing for your anonymous class, you can use dynamic, like this:

static object MakeAnonymous() {
return new {a = "3", b = "4"};
}
static void Main(string[] args) {
dynamic test = MakeAnonymous();
Console.WriteLine("{0} {1}", test.a, test.b);
}

The downside to this approach is that the compiler is not going to help you detect situations when a property is not defined. For example, you could write this

Console.WriteLine("{0} {1}", test.abc, test.xyz); // <<== Runtime error

and it would compile, but it would crash at runtime.

Accessing C# Anonymous Type Objects

As the other answers have stated, you really shouldn't do this. But, if you insist, then there's a nasty hack known as "cast by example" which will allow you to do it. The technique is mentioned in a couple of articles, here and here.

public void FuncB()
{
var example = new { Id = 0, Name = string.Empty };

var obj = CastByExample(FuncA(), example);
Console.WriteLine(obj.Name);
}

private object FuncA()
{
var a = from e in DB.Entities
where e.Id == 1
select new { Id = e.Id, Name = e.Name };

return a.FirstOrDefault();
}

private T CastByExample<T>(object target, T example)
{
return (T)target;
}

(I can't take the credit for this hack, although the author of one of those articles says that he doesn't want to be associated with it either. His name might be familiar.)

How can I access a field in an anonymous type stored in an object variable?

Use the dynamic keyword:

public struct Foo
{
public dynamic obj;
public Foo(int val)
{
obj = new
{
bar = val
};
Console.WriteLine(obj.bar); // is accessible now
}
}

Access anonymous object property from static class c#

You need to cast it to the type of the object. Because you have non (at compile time) cast as dynamic:

var obj = Fields.FieldInfo1 as dynamic;
var value = obj.Customer.Prop1; // "value1"

But I don't see why you need to do it this way. This is not C# like, which is a strongly typed language. In my opinion you should rethink your design.

This might give you a starting point for when it is right to use anonymous types

How can I get a value of a property from an anonymous type?

Have you ever tried to use reflection? Here's a sample code snippet:

// use reflection to retrieve the values of the following anonymous type
var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
System.Type type = obj.GetType();
int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null);
string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null);

// use the retrieved values for whatever you want...

How to get the properties from a dynamic (Anonymous Type) object using reflection?

Get the first item, cast it to object, and then you can get the properties:

object e = collection.FirstOrDefault();
var columns = e.GetType().GetProperties().Length;

Or just:

collection.FirstOrDefault().GetType().GetProperties().Length;

Get value from anonymous type

Use this one:

string area = areaObject.GetType().GetProperty("area").GetValue(areaObject, null);

C# Anonymous Type access from other method

You can use reflection too.

private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (myComboBox.SelectedItem != null)
{
var x = myComboBox.SelectedItem;
System.Type type = x.GetType();
int id = (int)type.GetProperty("Id").GetValue(obj, null);
}
}


Related Topics



Leave a reply



Submit