object initializer and automatic properties

  • Thread starter Thread starter bill tie
  • Start date Start date
B

bill tie

Consider the following:

object myObject = new Object();
myObject = new { foo = "fooStr", bar = "barStr" };

How do I retrieve the value of foo from myObject?
 
bill tie said:
Consider the following:

object myObject = new Object();
myObject = new { foo = "fooStr", bar = "barStr" };

How do I retrieve the value of foo from myObject?

You can't. Note that this is using anonymous types, not object
initializers or automatic properties.

Anonymous types are usually used either within a context where the type
is propagated (e.g. LINQ) or with implicitly typed local variables,
e.g.:


var myObject = new { foo = "fooStr", bar = "barStr" };

string x = myObject.foo;
 
To simplify the riddle I tried to emulate a class that I had perused in the
Reflector. The class MAY look like this:

public class FunkyClass
{
public object FunkyProperty
{
get;
set;
}
}

....

myList.Add(new FunkyClass
{
FunkyProperty = new { foo = "fooStr", bar = "barString" }
}
);

What gives?
 
bill tie said:
To simplify the riddle I tried to emulate a class that I had perused in the
Reflector. The class MAY look like this:

public class FunkyClass
{
public object FunkyProperty
{
get;
set;
}
}

Right: *That* is an automatically implemented property.
myList.Add(new FunkyClass
{
FunkyProperty = new { foo = "fooStr", bar = "barString" }
}
);

And *that* is using an object initializer.
What gives?

I don't see what you mean. Previously you were using one particular
feature, now you're using two different ones. What's confusing you?
 
Actually, it is using all of auto-properties (get;set;}, an object
initializer ({FunkyInitialize=...}) and an anonymous type (new { foo =
"fooStr", bar = "barString" }).

Since the auto-property is typed as object there is no friendly way of
getting the properties, except for reflection / component-model:

var item = myList[0].FunkyProperty;
// (item is typed as "object" due to FunkyProperty)
foreach(PropertyDescriptor prop in
TypeDescriptor.GetProperties(item)) {
Console.WriteLine("{0}={1}", prop.Name,
prop.GetValue(item));
}

Marc
 
One other thought; you might want to verify the syntax isn't actually
more like:

var myList = new Dictionary<int, string> {
{1,"abc"}
};

This is the more general form of a collection-initializer, meaning
call .Add(1,"abc")

Just a thought...

Marc
 
Marc Gravell said:
Actually, it is using all of auto-properties (get;set;}, an object
initializer ({FunkyInitialize=...}) and an anonymous type (new { foo =
"fooStr", bar = "barString" }).

Whoops - hadn't seen the anonymous type part. Doh!
 
Back
Top