Ollegn Ollegn - 4 months ago 26
C# Question

Stucture across multiple files

I'm making a simple game that has Stats(strength, intelligence, charisma...) and Skills(Mining,Swim,Ride...). These structures are organized in class

Types
.

I want to reach those structures across all the files. In C++ I could just include the class and use the struct Stats, but I can't do the same in C#.

Is there a way to make this work?

This is my simplified code

public class Types{
public struct stats{
float str;
float con;
float inte;
}

public struct skill{
float mining;
}
}

public class NPC{
stats baseStats;
skill skills;
string name;
float hunger;
float necessity;
short hp;
}


Thanks.

Answer

Because the structs are nested inside the class Types you need to prefix the declaration of the structs instances with the nesting class name

public class NPC
{
    Types.stats baseStats;
    Types.skill skills;
    string name;
    float hunger;
    float necessity;
    short hp;
}

Now, if you need to use these types between different namespaces you need to add the appropriate using at the beginning of the file.

namespace MyTypes
{
    public class Types
    {
        public struct stats
        {
            float str;
            float con;
            float xxx;
        }

        public struct skill
        {
            float mining;
        }
    }
}
.....


using MyTypes;
namespace MyNPC
{
    public class NPC
    {
        Types.stats baseStats;
        Types.skill skills;
        string name;
        float hunger;
        float necessity;
        short hp;
    }
}

Moreover, if the types are in different projects files you need to add the reference to the relative project that contains the declarations.