C # class static class with members

I have several classes with static member:

class BuildingA{
   static BuildableComponent buildableA;
}

class BuildingB{
   static BuildableComponent buildableB;
}

      

This static member has its own members:

class BuildableComponent{
    int cost;
}

      

I would like to be able to manipulate static members through the BuildingA and BuildingB classes, for example A.buildableA.cost and B.buildableB.cost - the way I described it doesn't quite work, but is there a way to do this?

+3


source to share


2 answers


Fields are private by default in C # - you need to add an access modifier to it public

:

class BuildableComponent
{
    public int cost;
}

      

But as recommended by @EamonnMcEvoy, you can do this with a property:

class BuildableComponent
{
    public int Cost { get; private set; }
}

      

Properties are recommended because you can make the field readable from other classes without letting other classes change the property (as I did above by making the setter private). They have other advantages, one of which is that they can be overridden in derived classes if needed.



In C # 6, you can also omit the setter entirely, forcing the value to be set only from the constructor, and making the property immutable:

class BuildableComponent
{
    public BuildableComponent(int cost)
    {
        Cost = cost;
    }

    public int Cost { get; }
}

      

You have an additional problem that the margins are BuildableComponent

inside BuildingA

and BuildingB

are equal static

. This means that they belong to the class, not an instance of the class (i.e., every instance of the class has the same value). This means that you need to access it via the class name, not an instance of the class:

int cost = BuildingA.buildableA.cost;

      

In this particular case, I would like to ask myself if you want this component to be static. If you are going to create multiple instances BuildingA

, do you want them to share the same components? If not, make them non-static.

+3


source


In C #, class members are equal by default private

, so cost

only accessible from an instance BuildableComponent

.

You need to add an access modifier public

to the field, cost

or better yet, make it proprietary with get and set:

class BuildableComponent{
    public int cost;
}

      



OR

class BuildableComponent{
    public int Cost { get; set; };
}

      

+2


source







All Articles