0

Forgive me because I know my wording is terrible. I'll just give an example.

public class MainClass{
    public int someVariable;
    public List<HasAClass> cList = new List<HasAClass>();

    addHasAClass(HasAClass c){
        cList.Add(c);
    }

}
public class HasAClass{
    public HasAClass(){
        //Modify someVariable in some way????
    }
}
public class HasASubClass : HasAClass{
    public ComposedClass(){
        //Modify someVariable in some way???
    }
}

I having trouble finding the right words for this questions but here is what I am trying to do: I am creating an aid for an RPG similar to dungeons and dragons. Each character can have a variety of special abilitys which can effect the characters in some way (both negative and positive). I am trying do this with a variety of subclasses which store the pertinent info and get added to the character at varying points in time. What I can't figure out is how to modify the properties of the Character(I called it Main Class in my example) when instances of the HasA class are added to it.

4
  • Do it from the addHasAClass function, in MainClass.
    – Blorgbeard
    Mar 1, 2015 at 21:43
  • @Blorgbeard I couldn't really do it from there. My example is not really complex enough. There are a lot of properties in the main class. Each one of the 40+ HasA class modifies different values, as well as contains other info.
    – MichelleJS
    Mar 1, 2015 at 22:00
  • 1
    You need to pass "parent"/"container" object to child/sub-element one... Note that it may be better to ask child object about changes ("eachChild.ModifyArmorRating(ref computedArmorRating)") instead of pushing changes into parent class deepening on your design/needs. Mar 1, 2015 at 22:00
  • @AlexeiLevenkov I think I see where you are going with that, and I think you are right. I'm going to try that. I need to think about which version will be less complicated but I think it will be pushing the changes into the parent class.
    – MichelleJS
    Mar 1, 2015 at 22:05

1 Answer 1

0

The HasAClass needs a reference to the owning instance, so that it can ask the parent for values and update them when required...

public class HasAClass
{
    private MainClass _mainClass;
    public HasAClass(MainClass mainClass)
    {
        _mainClass = mainClass;
        _mainClass.someVaraible = 42;
    }
}

You then need to pass the owner reference into the constructor of the HasAClass when they are created. If this is not possible at the time of creating the instance then you would instead need to assign it as a property after it has been created. Such as inside the addHasAClass method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.