How to Access Property of Anonymous Type in C#

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 */ });

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;

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 to read a property of an anonymous type?

The simplest approach would probably be to use dynamic typing:

dynamic foo = ret.Data;
Assert.AreEqual("OK", foo.status);

Note that you'll need to use [InternalsVisibleTo] in order to give your unit test assembly access to the anonymous type in your production assembly, as it will be generated with internal access.

Alternatively, just use reflection.

Get read/write properties of Anonymous Type

Anonymous types generated from C# are always immutable, so the set of writable properties is empty. In VB it's optional: each property defaults to being mutable, but if you prefix it with Key it's immutable; only properties declared using Key count for equality and hash code generation. Personally I prefer C#'s approach.

CanWrite isn't always returned as true for properties in non-anonymous types - only for writable ones. Properties can be read-only, write-only, or read-write. For example:

public class Test
{
// CanWrite will return false. CanRead will return true.
public int ReadOnly { get { return 10; } }

// CanWrite will return true. CanRead will return false.
public int WriteOnly { set {} }

// CanWrite will return true. CanRead will return true.
public int ReadWrite { get { return 10; } set {} }
}

Why can't I access properties of an anonymous type returned from a function via the dynamic keyword?

The problem is that anonymous types are internal, which means that you can't access their properties with dynamic property accessors from projects other than the one they were created in. The dynamic binding treats them as the closest public inherited type it knows about--object.

To fix this, you can declare a public type to represent the values you're expecting to find in your anonymous type. This is probably a good idea anyway, since you're clearly expecting to consume the returned properties in other parts of your code. Using a declared type also enables you to maintain type-safety, avoiding the need for dynamic entirely.

If you absolutely must use dynamics here, the next best option is probably to change your AssemblyInfo.cs file to make internal properties accessible to the project you're trying to access them from:

[assembly:InternalsVisibleTo("MyOtherProject")]

List of properties to anonymous Type

You cannot produce a new anonymous type at run-time, because anonymous types are actual types, produced by the compiler behind the scene. The code to produce these types is not available to users of .NET through the API, so you would have to go through System.Reflection.Emit calls to build your own.

The next closest thing would be using a dynamic object, such as the ExpandoObject, and set its values using the IDictionary<string,object> interface. The callers would be able to access fields of this object using the regular syntax.

EDIT : If all you need is a collection of property values in a way that you can access at run-time, you could use Dictionary<string,object>, like this:

generals.Select(x =>
properties.ToDictionary(p => p.Name, p => p.Invoke(x))
);


Related Topics



Leave a reply



Submit