Reputation: 2069
I'm looking for a best way to fill the object properties. This is the situation:
I need to send an object to a dll method, this object have a default name properties (that I'll show later). Actually for valorize all the properties dinamicall I've created a dictionary first, like this:
IDictionary<string, string> user = new Dictionary<string, string>();
later in the add
method I ask to user to insert the value like this:
Console.WriteLine("Insert user name:");
user["name"] = Console.ReadLine(); //valorized dictionary index
Console.WriteLine("Insert surname: ");
user["surname"] = Console.ReadLine();
after this I add the dictionary index, to the object property:
object data = new{
name = user["name"],
surname = user["surname"]
};
User.add(data); //Send the user to add to rest resource..
How you can see this way, in my opinion is a bit long. I want avoid the use of the dictionary and push the data in the object directly, is possible do this? Is not, there is another way to achieve the result more fast? Thanks in advance.
Upvotes: 2
Views: 57
Reputation: 156948
You can use the ExpandoObject
which is a middle way between a dictionary and an object (actually it is an object where you can dynamically set the properties which are stored in a backing dictionary).
dynamic u = new ExpandoObject();
u.name = "abc";
You can even pass in u
in a method as a dictionary:
Method(u);
private void Method(IDictionary<string, object> d)
{
string name = (string)d["name"];
}
Upvotes: 4
Reputation: 5144
You could use dynamic ExpandoObject
if it fits your needs:
dynamic user = new ExpandoObject();
user.name = Console.ReadLine();
Console.WriteLine("Insert surname: ");
user.surname = Console.ReadLine();
User.add(user);
Later on, you can also use underlying dictionary to dynamically access properties:
var dict = (IDictionary<String, Object>)user;
dict["name"] = "John";
Debug.WriteLine(dict["name"]); // Outputs John
Debug.WriteLine(user.name); // Outputs John
Upvotes: 4