Sign in to follow this  

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

This topic is 2458 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:

[code]
Character c = new Character();
c.Stats.Strength = 3;
[/code]


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

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

}
[/code]


Is there a better way?

Share this post


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

[code]
class StatsClass
{
public int Strength { get; set; }
}
[/code]

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
[quote name='Lesan' timestamp='1298491111' post='4778101']
Is there a better way?
[/quote]
If you are only going to have a set # of stats, something like:

[code]

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);

}
}[/code]

Share this post


Link to post
Share on other sites

This topic is 2458 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this