Hello!
I want to create an object as a property within the class and access properties of the sub class...
My problem is if I want to create several objects of the sub class i am not able to do that
Can anyone suggest me somesolution to this ?
Please ...
Loading

Alex38 reputationPosted Aug 15, 2008, 2:38 PM EDT
public SubObject Foo
{
get
{
return new SubObject();
}
}
Now, every time you access the Foo property, you have a new instance of the sub object.
Abhay Mhatre27 reputationPosted Aug 15, 2008, 2:41 PM EDT
thank you very much
Abhay Mhatre27 reputationPosted Aug 15, 2008, 2:44 PM EDT
I mean I want to assign values to properties of subObject
AlanRank #669 · 3.6K reputationPosted Aug 16, 2008, 4:07 AM EDT
Just expanding a bit on Alex's example, you could do this:
public ParentObject
{
private SubObject foo;
public SubObject Foo
{
get
{
return foo;
}
set
{
foo = value;
}
}
}
public SubObject
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
// code to set Foo property
ParentObject po = new ParentObject();
SubObject so = new SubObject();
so.Name = "Abhay";
po.Foo = so;
// code to get Foo property
SubObject so2 = po.Foo;
string name = so2.Name;
If you may want to include several SubObjects within ParentObject, then declare the property (and backup field) as being of type SubObject[] or List rather than just SubObject.