I am using an object initializer for a st
object:
public class Container
{
public Container () { ContainedItem = new Item; }
public Item ContainedItem { get; set; }
}
public class Item
{
public string Value { get; set; }
}
var MyContainer = new Container()
{
// I want to populate the the property Value of the property Item
// with the second line rather than the first
ContainedItem = new Item() { Value = FooString }, // This works
ContainedItem.Value = FooString // This assigns to the same member but does not work
};
The second initializer line gives the error:
The name 'ContainedItem' does not exist in the current context.
Invalid initializer member declarator.
and suggests declaring ContainedItem
somewhere in local scope.
Now as the first line works it can be seen that ContainedItem
is in fact a valid property of Container
and that MyContainer.ContainedItem
is definitely not null... so why does the following line fail to recognise it?
c
is a property ofs
,x
is a property ofc
– Ingeniousst
andct
class definitions are. – Adulteressst
orct
? Including both lines like that makes it unclear whether that's what you want or whether you only want the second line, on its own. Fundamentally, you're simply trying syntax that doesn't exist, but it would be easier to help you if you were clearer about what you were trying to achieve. (If you do want to initializec
so a specific value and modify that value, then just use an object initializer for that as you've already shown you can do...) – TiddlyItem
property at all, or are you trying to set it and then modify it in a second line? If it's the former, my answer shows what you want. If it's the latter, I fail to see why you'd want to do that a separate item in the object initializer when you can do it in the object initializer fornew Item
. – TiddlyItem = new Item;
isn't valid, and you don't have a;
after the declaration ofValue
. It's not clear why you've taken my valid example and made it invalid (and introduced public fields instead of properties at the same time... urgh) – Tiddly