Pass a C# dynamic object to a method that takes an IDictionary - c#

Right now, I'm doing this
var data = new JobDataMap(new Dictionary<string,string> { {"obj", "stringify"} });
But I want to do this:
dynamic d = new { obj = "stringify" };
var data = new JobDataMap(d);
Is there some secret syntactical sugar that would allow me to do this?

There's no magical way of doing this. There's no way the compiler can know that your Dynamic object really is a Dictionary at compile time.
That being said, you could create an extension method that converts it to a Dictionary so that you could do something like this:
dynamic d = new { obj = "stringify" };
var data = new JobDataMap(d.ToDictionary());
This blogpost offers an example: http://blog.andreloker.de/post/2008/05/03/Anonymous-type-to-dictionary-using-DynamicMethod.aspx

Related

How to use dynamic Linq with List object

I have List object of type dynamic like List<dynamic> but when I try to use it with Linq then it's not working. Below is my Linq syntax
var tt = lst.Where(x => (string)x.Type == "test");
So how can I use dynamic Linq on List having type as dynamic object.
It throws an error:
'System.Collections.Generic.List<object>' does not contain a definition for 'Type'
Make sure you have declared the dynamic type correctly or is there any mismatch between the objects. I just tried the same thing and it works for me.
dynamic obj = new {
Data = "sjds"
};
dynamic obj2 = new {
Data = "sjdsf"
};
List<dynamic> dynamics = new List<dynamic>();
dynamics.Add(obj);
dynamics.Add(obj2);
var str = dynamics.Where(x => x.Data == "sjds");
If your case different than this you can share the full code to better understand the scenario.
The compiler has no way to know what your dynamic objects look like. Therefore you need to tell the compiler by casting to a type. Since you're assuming that a particular property exists on your dynamic object (Type), you can try and cast it.
List<YourType> yourList = lst as List<YourType>;
if (yourList!=null){
var filtereList = yourList.Where(x=>x.Type.Equals("test"));
}

Add value to object type c#

I've have object like this:
object rt = new {
page = 1,
};
Now how could I add new values to this object? I mean something like this:
rt += { code = 5 };
How it could be possible?
It sounds more like you want a Dictionary<string,int>
var rt = new Dictinary<string,int>(){
{"page",1}
};
rt.Add("code",5);
You can also do it with System.Dynamic.ExpandoObject - but this is just a fancy wrapper around a dictionary.
dynamic rt = new ExpandoObject();
rt.page = 1;
rt.code = 5;
Console.WriteLine(rt.page);
Use ExpandoObject
dynamic rt = new ExpandoObject();
rt.page = 1;
rt.code = 5;
The actual question is: why do you need this at all? Imagine your object was a named one, e.g. like this:
var m = new MyClass { MyProperty = ... };
with
class MyClass
{
public string MyProperty;
}
What you want to do is, to add a further property to that class at runtime, which isn´t possible. You can´t do the following:
m.AnotherProperty = ...
as AnotherProperty isn´t defined on that type.
Even declaring m as dynamic wouldn´t help you, as the actual type (MyClass) doesn´t know anything of AnotherProperty.
dynamic a = new MyClass { MyProperty = ... };
a.AnotherProperty = ...;
So the simple answer to your question is: no, you can´t add members to a class at runtime.

Adding properties to an object dynamically

I was trying to create objects at runtime. We have .net framework provided classes like DynamicObject and ExpandoObject. Is it possible to create a dynamic object like this
dynamic obj = new expandoObject();
obj["propName1"] = "name"; //string type
obj["propName2"] = 24; //int type
I dont know the property names until runtime. Is it possible to do this way?
Well, two things.
First, yes, you can stuff values into the ExpandoObject object using "property names" contained in strings, because it implements IDictionary<string, object>, so you can do it like this:
void Main()
{
dynamic obj = new ExpandoObject();
var dict = (IDictionary<string, object>)obj;
dict["propName1"] = "test";
dict["propName2"] = 24;
Debug.WriteLine("propName1=" + (object)obj.propName1);
Debug.WriteLine("propName2=" + (object)obj.propName2);
}
Notice how I use the property syntax to retrieve the values there. Unfortunately, dynamic is like a virus and propagates, and Debug.WriteLine is none too happy about dynamic values, so I had to cast to object there.
However, and this is the second thing, if you don't know the property names until runtime, those last two lines there won't appear anywhere in your program. The only way to retrieve the values is again to cast it to a dictionary.
So you're better off just using a dictionary to begin with:
void Main()
{
var obj = new Dictionary<string, object>();
obj["propName1"] = "name";
obj["propName2"] = 24;
Debug.WriteLine("propName1=" + obj["propName1"]);
Debug.WriteLine("propName2=" + obj["propName2"]);
}

C# object creator

In javascript, I often use something like this object creator
var o = new Object(); // generic object
var props = { color:"red",value:5 }; // hashtable
for(var key in props) o[key] = props[key];
alert(o.color); //red
Can it be written as C# method with this declaration?
static void properties(out Object o, HashTable h) { ...
Is this some design pattern? Am I inventing wheel?
You may want to look at the Expando Object in C# 4. That is about as close as you are going to get to a dynamic object in C# like you can get in JavaScript.
http://msdn.microsoft.com/en-us/magazine/ff796227.aspx
http://www.c-sharpcorner.com/blogs/BlogDetail.aspx?BlogId=2134
var test = new { name = "Testobj", color = Colors.Aqua };
MessageBox.Show(test.name);
It's called a anonymous Type, I think this is what you are searching for.
Since c# is statically typed, you cannot achieve this.. closest possible is anonymous methods
Dictionary<string,int> dic=new Dictionary<string,int>();
dic.Add("red", 5);
dic.Add("black", 10);
dic.Add("white", 1);
object[] obj;
foreach(var o in dic)
{
var sam= new { color = o.Key,value=o.Value };
Console.WriteLine(sam.color);
}

Is it possible to create an object instance based on a string value denoting its type?

I'm trying to dynamically create an object of a certain type in a LINQ-to-XML query based on a string within my XML document. I'm used to being able to dynamically create an object of any type in PHP and JavaScript by simply being able to write something like:
$obj = new $typeName();
Ideally, I'd like to be able to do something like:
List<someObj> = (from someObjs in XMLfile
select new someObj()
{
Name = (string)someObjs.Element("name"),
NestedObj = new someObjs.Element("nestedObj").Element("type")()
{
NestedName = (string)someObjs.Element("nestedObj").Element("name")
}
}).ToList();
I just can't figure out how to do it without grabbing a hold of the current executing assembly.
You can use:
Activator.CreateInstance(Type.GetType(typeName))
Of course, this only works for types with a parameterless constructor.
Update (initializing the object):
You can use C# 4 dynamic typing features to set properties of the newly created object:
dynamic newObj = Activator.CreateInstance(Type.GetType(typeName));
newObj.NestedName = str;
In the context of a LINQ to XML query, you may have to resort to lambda syntax with explicit body:
var list = XMLFile.Select(someObjs => {
dynamic nestedObj = Activator.CreateInstance(
Type.GetType(someObjs.Element("nestedObj").Element("type")));
nestedObj.NestedName = (string)someObjs.Element("nestedObj").Element("name");
return new someObj {
Name = (string)someObjs.Element("name"),
NestedObj = nestedObj
};
}).ToList();
Use the createinstance method of activator class

Categories