Is it possible to build dynamic objects having the property name set to the value of a variable?
for instance this seems standard...
dynamic elem = new Object();
elem.Name = "myName";
but how would this be implemented?...
string fn = "FirstName";
string ln = "LastName";
dynamic elem = new Object();
elem.fn = "John";
elem.ln = "Doe";
where as i would be able to call the properties like...
string fn = elem.FirstName;
The ExpandoObject also implements IDictionary<string, object>, meaning you can add properties using a string key.
dynamic person = new ExpandoObject();
person.FirstName = "Alex";
var ln = "lastname";
(person as IDictionary<string, Object>)[ln] = "KeySmith";
Related
I want to create a single object (possibly Dictionary) with string keys that will have different variable types as the value (string, int, bool, Dictionary<string,string> etc). Is this possible?
*I understand this might just be a fundamental difference of two languages AKA square peg round hole
You can use dynamic as values type, that match better than object to the question and you need no future castings:
var dictionary = new Dictionary<string, dynamic>();
dictionary.Add("1", 10);
dictionary.Add("2", "test");
dictionary.Add("3", true);
foreach ( var item in dictionary )
Console.WriteLine($"{item.Key} is type: {item.Value.GetType().Name} = {item.Value}");
Console.WriteLine();
int v = dictionary["1"] + 10;
Console.WriteLine(v);
string s = dictionary["2"] + " one";
Console.WriteLine(s);
bool b = !dictionary["3"];
Console.WriteLine(b);
Output
1 is type: Int32 = 10
2 is type: String = test
3 is type: Boolean = True
20
test one
False
https://learn.microsoft.com/dotnet/csharp/programming-guide/types/using-type-dynamic
A Dictionary<string, object> is roughly equivalent to an object in JavaScript.
Example:
var dictionary = new Dictionary<string, object>
{
"myString" = "helloWorld",
"myChild" = new Dictionary<string, object>
{
"myName" = "bobby tables"
}
};
var myString = (string)dictionary["myString"];
var myName = (string)((Dictionary<string, object>)dictionary["myChild"])["myName"];
You can also use the dynamic keyword and ExpandoObject.
dynamic obj = new ExpandoObject();
obj.MyString = "helloWorld";
obj.MyChild = new ExpandoObject();
obj.MyChild.MyName = "bobby tables";
string myString = obj.MyString;
string myName = obj.MyChild.MyName;
Trying to get address and its value to be curly brackets. means json object within a json object.
var jsonObject = new JObject();
dynamic j_obj = new JObject();
j_obj.jsonrpc = "1.0";
j_obj.id = "abc";
j_obj.method = "getrawtransaction";
j_obj.#params = new JArray() as dynamic;
dynamic info = new JObject();
info.txid = "myid";
info.vout = "0";
j_obj.#params.Add(info);
var address = "myaddress";
j_obj.Add(new JProperty(address, "0.01"));
Console.WriteLine(j_obj.ToString());
What I want is "address" and its value to be json object.
This is the output I am getting now.
Output Image
You are adding a value property here
var address = "myaddress";
j_obj.Add(new JProperty(address, "0.01"));
Instead create an object for the address then use that in the property:
dynamic addressItem = new JObject();
addressItem.line1 = "foo";
var address = "myaddress";
j_obj.Add(new JProperty(address, addressItem));
Alternatively, as you have gone down the dynamics route you could do this
j_obj.myaddress = new
{
line1 = "foo"
}
Either of these would create JSON that looks like this:
{
...
"myaddress": { "line1": "foo" }
...
}
I need to pass object of one class as parameter in other class dynamically. I have following code which has to be customize.
ABC abc = new ABC();
abc.id = "E100";
abc.type = ABCType.BB_UNIQUE;
abc.typeSpecified = true;
ABC t = new ABC();
t.id = "I";
t.yellowkey = MarketSector.Equity;
t.yellowkeySpecified = true;
t.type = ABCType.t;
t.typeSpecified = true;
ABC abc2 = new ABC();
abc2.id = "GB";
abc2.type = ABCType.ISIN;
abc2.typeSpecified = true;
ABCs i = new ABCs();
i.abc = new abc[] { abc, abc2, t };
I was able to as follows To dynamically create the class object but i am not able to pass it to another class:
string value = "E100,I";
string[] id;
id = value.Split(',');
IDictionary<string, ABC> col = new Dictionary<string, ABC>();
foreach (string val in id)
{
col[val] = new ABC();
col[val].id = val;
}
ABCs i = new ABCs();
This part is where i am struggling
i.abc = new abc[] { abc, abc2, t };
How will i be able to pass dynamic object of IDictionary to i.abc?
Any help will be appreciated
Thanks
The IDictionary<TKey, TValue> interface has a Values property for every value contained in the IDictionary<TKey, TValue> which returns an ICollection<TValue>.
After including the System.Linq namespace, the ICollection<T> interface gets an extension method ToArray<T>() which converts the collection to an array of type T.
So the solution for your problem should be the following line:
i.abc = col.Values.ToArray();
I have an object:
MyObject obj = new MyObject();
obj.X = "Hello";
obj.Y = "World";
Someone passes me a string:
string myString = "obj.X";
I want to get the value referenced to myString, like this:
var result = <Some Magic Expression>(myString); // "Hello"
Is it possible through reflection?
You can't exactly replicate this behaviour, because names of local variables aren't saved in the method's metadata. However, if you keep a dictionary of objects, you can address the object by its key:
public static object GetProperty(IDictionary<string, object> dict, string path)
{
string[] split = path.Split('.');
object obj = dict[split[0]];
var type = obj.GetType();
return type.InvokeMember(split[1], BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.GetProperty, null, obj, null);
}
var dict = new Dictionary<string, object>();
var cl = new MyClass();
dict["obj"] = cl;
cl.X = "1";
cl.Y = "2";
Console.WriteLine(GetProperty(dict, "obj.X"));
Console.WriteLine(GetProperty(dict, "obj.Y"));
This can handle accessing fields and properties in the format "name.property". Doesn't work for dynamic objects.
i have this
dynamic d = new ExpandoObject();
d.Name = attribute.QualifiedName.Name;
so , i know that d will have a property Name. Now if i don't know the name of the property at compile time , how do i add that property to the dynamic.
i found this SO Question
so, there is this complicated concept of call binders etc..which is tough to get in the first place.any simpler way of doing this ?
dynamic d = new ExpandoObject();
((IDictionary<string,object>)d)["test"] = 1;
//now you have d.test = 1
Here is a cleaner way
var myObject = new ExpandoObject() as IDictionary<string, Object>;
myObject.Add("Country", "Ireland");
You can also do like this:-
Dictionary<string,object> coll = new Dictionary<string,object>();
coll.Add("Prop1","hello");
coll.Add("Prop2",1);
System.Dynamic.ExpandoObject obj = dic.Expando();
//You can have this ext method to better help
public static ExpandoObject Expando(this IEnumerable<KeyValuePair<string, object>>
dictionary)
{
var expando = new ExpandoObject();
var expandoDic = (IDictionary<string, object>)expando;
foreach (var item in dictionary)
{
expandoDic.Add(item);
}
return expando;
}