C# object creator - c#

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);
}

Related

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"]);
}

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

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

Can I pass arbitrary number of named parameters to function in C#?

Is there some kind of equivalent of Python's **kwargs in C#? I would like to be able to pass variable number of named arguments into functon, then get them as something Dictionary-like inside function and cycle over them.
There is nothing in C# available to let you pass in arbitrary named parameters like this.
You can get close by adding a Dictionary<string, object> parameter, which lets you do something similar but requiring a constructor, the "parameter names" to be strings and some extra braces:
static void Method(int normalParam, Dictionary<string, object> kwargs = null)
{
...
}
Method(5, new Dictionary<String, object>{{ "One", 1 }, { "Two", 2 }});
You can get closer by using the ObjectToDictionaryRegistry here, which lets you pass in an anonymous object which doesn't require you to name a dictionary type, pass the parameter names as strings or add quite so many braces:
static void Method(int normalParam, object kwargs = null)
{
Dictionary<string, object> args = ObjectToDictionaryRegistry(kwargs);
...
}
Method(5, new { One = 1, Two = 2 });
However, this involves dynamic code generation so will cost you in terms of performance.
In terms of syntax, I doubt you'll ever be able to get rid of the `new { ... }' wrapper this requires.
If you specifically want a series of KeyValuePairs instead of an array of values, you could do something like this:
public class Foo
{
public Foo(params KeyValuePair<object, object>[] myArgs)
{
var argsDict = myArgs.ToDictionary(k=>k.Key, v=>v.Value);
// do something with argsDict
}
}
myArgs would be an array of KeyValuePair<object, object> that you can iterate or convert to a dictionary as shown above. Just a note though, the conversion to dictionary might fail if you pass multiple KeyValuePair<>s with the same key. You might have to do some checking ahead of time before converting to a dictionary.
You would call it like this:
KeyValuePair<object, object> myKvp1 = new KeyValuePair<object, object>(someKey1, someValue1);
KeyValuePair<object, object> myKvp2 = new KeyValuePair<object, object>(someKey2, someValue2);
KeyValuePair<object, object> myKvp3 = new KeyValuePair<object, object>(someKey3, someValue3);
Foo foo = new Foo(myKvp1, myKvp2, myKvp3);
Yes. The ability to use optional and named parameters was added in, I believe, C# 4.0.
http://msdn.microsoft.com/en-us/library/dd264739(v=vs.100).aspx
void paramsExample(object arg1, object arg2, params object[] argsRest)
{
foreach (object arg in argsRest)
{ /* .... */ }
}
call it like this,
paramsExample(1, 0.0f, "a string", 0.0m, new UserDefinedType());
You can use a param list as your final argument to the function, like this:
void paramsExample(object arg1, object arg2, params object[] argsRest) {
foreach (object arg in argsRest)
{ /* .... */ }
}
the method can be invoked with any number of arguments of any type.
paramsExample(1, 0.0f, "a string", 0.0m, new UserDefinedType());
This is a strongly typed argument so if I wanted to use a list of strings I could do this:
public string Concat(string separator, params string[] strings) {
string result = "";
for (int i = 0; i < strings.Length; i++) {
if (i > 0)
result += separator;
result += strings[i];
}
return result;
}
To invoke:
MessageBox.Show(Concat("+", "Anders", "Eric", "Scott", "Duncan") + " = great team");
Check out more info here:
http://blogs.msdn.com/b/csharpfaq/archive/2004/05/13/how-do-i-write-a-method-that-accepts-a-variable-number-of-parameters.aspx

how to add an item to a object initialized with { blah = "asdf" }

how to add an item to an object initialized with:
object obj = new { blah = "asdf" };
If I want to add another key value pair, how would i?
You can't modify the object's anonymous type definition once you make the object using that initializer syntax. That is, once you initialize it with { blah = "asdf" }, it only has that blah property. You can't add another. This is because anonymous types are static types.
The ExpandoObject answers work though, for a dynamic object. See the other answers for that.
If you're really just trying to manage a collection of key-value pairs (kinda sorta based on the way you phrased your question), use a dictionary.
var kvp = new Dictionary<string, string>
{
{ "blah", "asdf" }
};
kvp.Add("womp", "zxcv");
#BoltClock is right on. Another alternative is to use an ExpandoObject, at the loss of intellisense.
dynamic obj = new ExpandoObject();
obj.blah = "asdf";
// sometime later
obj.somethingelse = "dfgh";
// obj now has 'blah' and 'somethingelse' 'properties'
Once you define an object like that, you're done. You can't add anything to it.
If you're using C# 4.0, though, you could always use a dynamic type:
dynamic obj = new ExpandoObject();
obj.blah = "asdf";
obj.blahBlah = "jkl;";

Categories