0

I have the following class

public class MyTestClass
{

    public string Name { get; set; }

}

and I do the following: 

dynamic myClass = new MyTestClass;

string propName = "Name";

And I want to be able to do this:

 myClass.propName = "Hello";

How can I convert the string into a propertyName using Dynamics? I know ways of doing it using reflection, but I would like to know for my knowledge if there is a way this can be achieved using dynamics or expando object?

7
  • MyTestClass doesn't have a property called propName How'll you do that using reflection? Can you show us? Commented Apr 9, 2014 at 3:00
  • that is amazing...how did you do that? Commented Apr 9, 2014 at 3:10
  • Can you indicate more generally what you are trying to accomplish? Why do you want to dynmically add a property? Commented Apr 9, 2014 at 3:11
  • Can I understand that you are going to assign the "Hello" to a dynamic generated property of MyTestClass? Commented Apr 9, 2014 at 3:12
  • I meant doing like this: stackoverflow.com/questions/11824362/… Commented Apr 9, 2014 at 3:15

1 Answer 1

2

I think you can use DynamicObject, but it would be a little bit different than what you're wanting. I am not sure that what you're wanting to do is possible in C# (definitely possible in other languages though). This is a pseudocode attempt at something (maybe not the most amazing piece of code)

public class MyDynamicObject<T> : DynamicObject {
    private T referenceObject;

    public MyDynamicObject<T>() {
        this.referenceObject = new T();
    }

    public override bool TrySetMember(SetMemberBinder binder, Object value) {
        var propertyName = // get from binder parameter
        typeof(T).SetValue(referenceObject, value);
    }

    public T Compile() {
        return referenceObject;
    }
}

Then I believe you can do something like:

var propertyName = "Name";
var dynamicObject = new MyDynamicObject<MyTestClass>();
dynamicObject[propertyName] = "Foo";
var myTestClass = dynamicObject.Compile();

Overall, I would say that you should investigate the DynamicObject functionality. The function that I overrode may not be the correct one for an array (I always forget which function to override). But you should give it a shot. If you want to see a really sweet project that uses DynamicObjects in the best way possible, check out https://github.com/markrendle/Simple.Data

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.