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.
Related
This question already has answers here:
What's the difference between an object initializer and a constructor?
(8 answers)
Closed 7 years ago.
I have the following class:
public class TestClass {
public string ClassName {
get;
set;
}
}
What's the difference between doing:
var instance = new TestClass();
and doing
var instance = new TestClass { };
I thought you needed to include the () to call the object's constructor. What does that mean?
Edit: Can someone explain which is best? Or if one ignores the constructor, benefits or disadvantages?
Edit2: Sorry if I asked something that was already answered. The difference was somewhat clear to me, but I really didn't understand how I could mix and match () and {}, since sometimes the () are ignored and I wanted to know when I could do so
The first example instantiates a new instance.
The second example instantiates a new instance via object initialization syntax.
They both end up creating a new instance.
You would use the latter if you needed or wanted to set a public property or field of your class during instantiation:
var instance = new TestClass { ClassName = "TestingInstance" };
as opposed to
var instance = new TestClass();
instance.ClassName = "TestingInstance";
It is essentially "syntactic sugar" that makes your life a bit easier (and for some devs more explicit) when creating new objects and setting a lot of properties.
When using object initialization, the params () are optional but the braces {} and statement-ending semi-colon ; are required
The second piece of code is shorthand syntax for object initialization.
You would use the second syntax when you want to set properties on the object at the same time, like this:
var x = new SomeObject
{
Property1 = "What's this?",
Property2 = 42
};
You can combine as well:
var x = new SomeObject("Some constructor parameter", 17, true)
{
OtherProperty = 42
};
The code can be loosely translated to this:
var temp = new SomeObject("Some constructor parameter", 17, true);
temp.OtherProperty = 42;
var x = temp;
The second example, with the {}, allows you to set public properties and fields on the object. For instance:
System.Drawing.Point p = new System.Drawing.Point
{
X = 3,
Y = 5
};
There's little reason to use {} over () when there's nothing inside the {}.
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"]);
}
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
Is there an easy way to create and Object and set properties in C# like you can in Javascript.
Example Javascript:
var obj = new Object;
obj.value = 123476;
obj.description = "this is my new object";
obj.mode = 1;
try c# anonymous classes
var obj = new {
value = 123475,
description = "this is my new object",
mode = 1 };
there are lots of differences though...
#Valera Kolupaev & #GlennFerrieLive mentioned another approach with dynamic keyword
In case, if you want to create un-tyed object use ExpandoObject.
dynamic employee, manager;
employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
manager = new ExpandoObject();
manager.Name = "Allison Brown";
manager.Age = 42;
manager.TeamSize = 10;
Your other option is to use anonymous class , but this will work for you, only if you would use it in the scope of the method, since the object type information can't be accessed from outside of the method scope.
In C# you could do:
var obj = new SomeObject {
value = 123476,
description = "this is my new object",
mode = 1
};
EDIT: Holding this here pending clarification from OP as I may have misunderstood his intentions.
The way to do this is you use C# 4.0 Dynamic types like Expando Object... see this topic:
How to create a class dynamically
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);
}