Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add properties to an object with reflection in c #

I would like to create a method that receive 3 strings as parameter and return an object that contains three properties that they referred to these Strings.

Do not have an "old Object" to replicate. The properties should be created in this method.

Is to do this in C # with reflection? If so, how? Below is what you like and I am not able to do.

protected Object getNewObject(String name, String phone, String email)
{
    Object newObject = new Object();

    ... //I can not add the variables that received by the object parameter here.

    return newObject();
}
like image 817
Elton da Costa Avatar asked Oct 26 '25 03:10

Elton da Costa


2 Answers

If you want to add properties, fields etc. in dynamic, you may try using Expando class

http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx

 dynamic newObject = new ExpandoObject();

 newObject.name = name;
 newObject.phone = phone; 
 newObject.email = email
like image 52
Dmitry Bychenko Avatar answered Oct 29 '25 07:10

Dmitry Bychenko


protected dynamic getNewObject(String name, String phone, String email)
{
    return new { name = name, phone = phone, email = email };
}
like image 20
It'sNotALie. Avatar answered Oct 29 '25 09:10

It'sNotALie.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!