Florim Maxhuni
Florim Maxhuni

Reputation: 1421

dynamic in C#, seting property value

I nead to set a property for an object

Personi p = new Personi();//this class has a property Datelindja(DateTime)
p.Emri = "Florim";
p.Mbiemri = "Maxhuni";
SetValue(p, "Datelindja", DateTime.Now); //I nead these method. using dynamic keyword
Console.WriteLine(p.Ditelindja);

How do i implement this method that will set the value base on these parameters.

method signature

SetValue(dynamic orgObj, string property, dynamic value)

Sorry for my bad english.

Upvotes: 2

Views: 2904

Answers (2)

jbtule
jbtule

Reputation: 31809

The opensource project Dyamitey has a method Dynamic.InvokeSet that uses DLR plumbing to accomplish that. While in your example you can indeed use reflection since the object itself isn't an IDynamicMetaObjectProvider, but by using Dynamic (dlr) not only will it be more flexible but it will average 3x faster than reflection.

Dynamic.InvokeSet(p,"Datelindja", DateTime.Now)

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

I don't see why you would need dynamic here.
SetValue will need to use reflection:

void SetValue<TInstance, TValue>(TInstance orgObj, string property, TValue value)
{
    orgObj.GetType().GetProperty(property).SetValue(orgObj, value, null);
}

You could also write this method without generics, because they don't add any benefit in this case:

void SetValue(object orgObj, string property, object value)
{
    orgObj.GetType().GetProperty(property).SetValue(orgObj, value, null);
}

Upvotes: 3

Related Questions