views:

73

answers:

3
+1  Q: 

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?

+2  A: 

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

Kevin
+1  A: 
        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.

Tokk
Yes, this is almost it! Is there any way how to extract all "members" of anonymous type? Since it is not enumerable, foreach cannot be used.
Jan Turoň
A: 

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

            }
Ramesh Vel