How to set value for property of an anonymous object?

Related searches

this is my code for example:

var output = new
{
    NetSessionId = string.Empty
};

foreach (var property in output.GetType().GetProperties())
{
    property.SetValue(output, "Test", null);
}

It occurs an exception: "Property set method not found". I want to know how to create an anonymous type with properties which can be set.

Thanks.

Anonymous type properties are read only and they cannot be set.

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

Anonymous Types (C# Programming Guide)

C# Anonymous Types, Anonymous types in C# encapsulate a set of read-only properties in an object without Variable products is a collection of Product objects. Console.WriteLine (v.Amount + v.Message); Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ in C#. Anonymous types contain one or more public read-only properties.

How to set value for property of an anonymous object?

Because I was reminded today that nothing is truly immutable when using reflection in combination with knowledge on how certain things are implemented (backing fields for the read-only properties of anonymous types in this case), I thought it wise to add an answer illustrating how the property values of an anonymous object can be changed, by mapping them to their backing fields.

This method relies on a specific convention used by the compiler for naming these backing fields: <xxxxx>i__Field in .NET and <xxxxx> on Mono, with the xxxxx representing the property name. If this convention were to change, the code below will fail (note: it will also fail if you try to feed it something that is not an anonymous type).

public static class AnonymousObjectMutator
{
    private const BindingFlags FieldFlags = BindingFlags.NonPublic | BindingFlags.Instance;
    private static readonly string[] BackingFieldFormats = { "<{0}>i__Field", "<{0}>" };

    public static T Set<T, TProperty>(
        this T instance,
        Expression<Func<T, TProperty>> propExpression,
        TProperty newValue) where T : class
    {
        var pi = (propExpression.Body as MemberExpression).Member;
        var backingFieldNames = BackingFieldFormats.Select(x => string.Format(x, pi.Name)).ToList();
        var fi = typeof(T)
            .GetFields(FieldFlags)
            .FirstOrDefault(f => backingFieldNames.Contains(f.Name));
        if (fi == null)
            throw new NotSupportedException(string.Format("Cannot find backing field for {0}", pi.Name));
        fi.SetValue(instance, newValue);
        return instance;
    }
}

Sample:

public static void Main(params string[] args)
{
    var myAnonInstance = new { 
        FirstField = "Hello", 
        AnotherField = 30, 
    };
    Console.WriteLine(myAnonInstance);

    myAnonInstance
        .Set(x => x.FirstField, "Hello SO")
        .Set(x => x.AnotherField, 42);
    Console.WriteLine(myAnonInstance);
}

With output:

{ FirstField = Hello, AnotherField = 30 }
{ FirstField = Hello SO, AnotherField = 42 }

A slightly more elaborate version can be found here

Anonymous Types, In C# 3.0 something called anonymous types was introduced, this means There's a fun way to actually get the property value and that is by using code, and that is to set the return type to dynamic instead of object, like this: Anonymous types are still statically typed at compile time. I'd suggest looking into the dynamic language features, or sticking with your dictionary. Here is an example of loading up a dynamic object from a dictionary of key/values, then accessing it as if it was a statically typed object.

If you ever come across a situation where you need a mutable type, instead of messing around with the Anonymous type, you can just use the ExpandoObject:

Example:

var people = new List<Person>
{
    new Person { FirstName = "John", LastName = "Doe" },
    new Person { FirstName = "Jane", LastName = "Doe" },
    new Person { FirstName = "Bob", LastName = "Saget" },
    new Person { FirstName = "William", LastName = "Drag" },
    new Person { FirstName = "Richard", LastName = "Johnson" },
    new Person { FirstName = "Robert", LastName = "Frost" }
};

// Method syntax.
var query = people.Select(p =>
{
    dynamic exp = new ExpandoObject();
    exp.FirstName = p.FirstName;
    exp.LastName = p.LastName;
    return exp;
}); // or people.Select(p => GetExpandoObject(p))

// Query syntax.
var query2 = from p in people
             select GetExpandoObject(p);

foreach (dynamic person in query2) // query2 or query
{
    person.FirstName = "Changed";
    Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
}

// Used with the query syntax in this example, but may also be used 
// with the method syntax just as easily.
private ExpandoObject GetExpandoObject(Person p)
{
    dynamic exp = new ExpandoObject();
    exp.FirstName = p.FirstName;
    exp.LastName = p.LastName;
    return exp;
}

Playing with anonymous types in C#, The expression that used to initialize properties are not null, anonymous method, or a pointer type. You can also create an anonymous type array. It cannot be cast � It does beg the question of why you're not using a named type though. Anonymous types aren't really designed to be shared among different methods like this. EDIT: Note that if this is in a different assembly to the original code creating the object, you'll need to use [InternalsVisibleTo] as anonymous types are internal.

I had a similar scenario where I needed to assign an error code and message to numerous object types that all SHARE specific nested properties so I don't have to duplicate my methods for reference hoping it helps someone else:

    public T AssignErrorMessage<T>(T response, string errorDescription, int errorCode)
    {
        PropertyInfo ErrorMessagesProperty = response.GetType().GetProperty("ErrorMessage");
        if (ErrorMessagesProperty.GetValue(response, null) == null)
            ErrorMessagesProperty.SetValue(response, new ErrorMessage());

        PropertyInfo ErrorCodeProperty = ErrorMessagesProperty.GetType().GetProperty("code");
        ErrorCodeProperty.SetValue(response, errorCode);

        PropertyInfo ErrorMessageDescription = ErrorMessagesProperty.GetType().GetProperty("description");
        ErrorMessageDescription.SetValue(response, errorDescription);

        return response;
    }

    public class ErrorMessage
    {
        public int code { get; set; }
        public string description { get; set; }
    }

C# Anonymous Types, Anonymous Types were introduced in C# 3.0 (.Net Fw 3.0) Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type. Dealing with anonymous type within a function was easy and a great aid while programming but when it came to passing …

An easy way could be to serialize the anonymous object in a Json with NewtonSoft'JsonConverter (JsonConvert.SerializeObject(anonObject)). Then you can change the Json via string manipulation and reserialize it into a new anonymous object that you can assign to the old variable.

A little convolute but really easy to understand for beginners!

What is Anonymous Types in C#?, To set the value of an indexed property, call the SetValue (Object, Object, Object []) overload. If the property type of this PropertyInfo object is a value type and value is null, the property will be set to the default value for that type.

I have any array of (Pilot) objects with a (Hanger) property, which may be null, which itself has a (List<Plane>) property.For testing purposes, I want to simplify and 'flatten' this to an anonymous object with properties PilotName (string) and Planes (array) but not sure how to handle a null Hanger property or an empty PlanesList.

Given the following method: public static void SetPropertyValue(object target, string propName, object value) { var propInfo = target.GetType().GetProperty(propName,

In my previous post I described how the Build method can be used to customize how a single anonymous variable is created. A common customization is to set a property value during creation. In most cases, this can simply be done after the anonymous variable has been created (so the following is not an AutoFixture customization):

Comments
  • possible duplicate of set value of a property of an anonymous type using reflection / TypeDescriptor is it possible?
  • I suggest you take a look at the ExpandoObject Class.
  • As @AlexFilipovici indicated, you can change the property values on an anonymous object by changing the values of their backing fields. This is a fragile method that relies on knowledge of how these backing fields are named to establish the relationship between property and corresponding backing field. I just added an answer to illustrate how this can be done.
  • Alternatively, as a huge hack and at risk of making your code look weird, you can just make the properties of your anonymous object be arrays (of size 1). Then you can just get the array, and set a value to its first position.
  • Please referr to : stackoverflow.com/questions/2328676/…
  • The best answer. Thanks.
  • Then how does Json.NET do it? -- It can set property values on anonymous types, so, clearly it can be done.
  • Short answer: probably reflection. Long answer: I'm not sure the exact way JSON.NET implemented that, but it's possible to set a read-only property after initialization using reflection, expression trees and hand-crafted IL. You have to target the compiler-generated backing field though.
  • See @Alex's answer below!
  • This is extremely useful, thanks! It's not completely clear to me why anonymous types have to be (in theory) immutable. I was trying to write an automatic stored procedure caller which takes an anonymous input collection and an anonymous output collection (and does simple, automatic C# type to SqlDbType conversion for input and output arguments). This helped me to finish it. (Obviously, there are other ways to do this, but using anonymous types makes the calling syntax extremely simple and friendly to use.)
  • Since I don't know the properties in advance, I've slightly simplified this to take a property name rather than a lambda expression. I guess the advantage of using a lambda expression is automatic existence checking at compile time - but it's also a disadvantage in a context where you don't know what the member properties will be at compile time!
  • This answer is really cool :) I would give it thousand points if i could!
  • I think this doesn't work in the case where you need a typed null value? (i.e. an ExpandoObject can't support that, but an anonymous type can)