Jump to content
  • Advertisement
Sign in to follow this  
Lesan

[.net] (C#) Categories of properties inside classes

This topic is 2649 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a Character class that now has too many properties. I would like to group some properties (like Strength, Intelligence,...) together so that I could access them like this:


Character c = new Character();
c.Stats.Strength = 3;



So far, the only way I managed to find is this:


class StatsClass
{
public int Strength;
}
class Character
{
StatsClass Stats = new StatsClass();

}



Is there a better way?

Share this post


Link to post
Share on other sites
Advertisement
This is pretty standard code. It is generally recommended to avoid public fields in favor of public properties:


class StatsClass
{
public int Strength { get; set; }
}


This way, you can add more code into the property, if you ever need to, without breaking the public API.

Share this post


Link to post
Share on other sites

Is there a better way?

If you are only going to have a set # of stats, something like:



public enum StatNames
{
Strength,
Intelligence,
Dexterity
}

public class Stat
{
private int _value;
public const int MaxStatValue = 100;
public const int MinStatValue = 1;

public void IncreaseStat(int amount)
{

}

public void DecreaseStat(int amount)
{

}

//alternately, pass a + or - amount
public void AdjustStat(int amount)
{

}

}

class Entity
{
public Dictionary<StatNames, Stat> Stats;
}


static class Program
{
static void Main()
{

Entity entity = new Entity();

entity.Stats[StatNames.Strength].AdjustStat(10);

}
}

Share this post


Link to post
Share on other sites
Just keep in mind that enums are boxed when used as Dictionary keys, unless you implement your own IEqualityComparer.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!