In addition to solution 1:
You could:
1) Introduce a field "Parent" in your
Service-classes; of type
Device (or, bearing Sergey's comment on polymorphism in mind, maybe rather an interface that
Device implements).
2) Don't initialize the fields for the
Service-instances in
Device in the class-body but instead in the constructor.
3) Introduce an argument to the constructors of the service-classes; of type
Device (or that interface) and provide it in form of the
this-keyword in the constructor of
Device when initializing the fields for the
Service-instances.
If you can't follow me here, please ask.
Unrelated suggestions:
- Avoid public setters (for properties), here: Name, IPAddress, Port. Make them protected or private.
- Change the fields for the
Service-instances in
Device to properties (again, with non-public setters).
- Use C# naming rules: PascalCasing (starting with a capital) for all class members: Fields, Properties, Methods. camelCasing only for local identifiers.
edit: Picking up on Dave's answer, I think it could make sense to change your design a bit. Because this:
Device.Service2.executethis("VolumeUp");
..looks a bit fishy. Essentially it's the Service here that you're using, not the Device. And the Service is using the Device. But why is the Service then a member of Device? If you flipped this around, making Device a member of Service, it would look like this:
Device device1 = new Device(name, ipaddress, port);
Service2 service2 = new Service2(device1);
service2.executethis("VolumeUp");
..and you wouldn't have to access a parent's members from its child objects.