Best practice for passing data in C#?

Started by
4 comments, last by cjmarsh 6 years, 5 months ago

What are some good practices for passing around data in C#? What are the pros and cons of using custom container classes versus a list or a dictionary or array?

Advertisement

Lists are excellent for storing variable amounts of data of a specific type.

Dictionaries are excellent for storing variable amounts of data of a specific type when you need to index it by another type.

Arrays are excellent for storing a specific amount of data of a specific type.

Custom classes are excellent for storing variable or specific amounts of data of multiple types.

 

A good rule of thumb is this: don't reinvent the wheel. The List, Dictionary, and Array classes are highly optimized and the odds are they will work for most applications. That said, sometimes custom classes are just more convenient so don't be afraid to make them when you need them.

Also, I should point out that when "passing around" reference objects via function calls and the like you aren't actually passing the entire object, just a pointer to the object in memory. If you meant cross-class communication instead, that is a different beast, but I don't want to misinterpret what you said so feel free to ask for more details if that's the case.

Basically what cjmarsh said.  Use the standard System.Collections.Generic collections (List, Stack, Queue, Dictionary, HashSet) for most things and only make a custom collection if it has some special behavior you need.  You probably won't need any other collections for a long time.  The main container class I can think of that I've written myself is a priority queue for A*.

However, since I remember posting a reply in your thread about RPG stats (comparing dictionaries to classes-with-fields), I want to make sure we're on the same page:  When we say 'custom container class' we mean a type that's specifically meant to contain data (usually all of the same type), without the container caring about the semantics of any element (i.e. the Dictionary doesn't know that it's containing RPG stats; it just sees keys and values and doesn't care what they mean).  Usually every element in a container is treated the same way by the container's code.  In your thread about RPG stats, the suggestion I made about having each stat as a field in a class would NOT be considered a 'container' class.  Each field in a class like that has a specific meaning and is treated differently by the program.

Usually you can identify when something is a container class or not by if it has some of these typical functions: Add, Remove, Insert, Push, Pop, Peek, Enqueue, Dequeue, or a square-bracket indexer.  If it just has a bunch of fields that you can directly get or set then we don't typically call those containers.

Yeah I redid a bit of a class that holds Stats for a character and incorporated some of your advice. Though quick and dirty. It already feels better.
I added a bit of functionality but some of it is probably unnecessary. Handles lvl, exp, modifiers from status ailments or equipment etc.

So from what you are saying it would probably be best to pass stats or other data in dicts lists or arrays? Ex: StatSheet.Get can send a dictionary<statID, value>



	public class StatSheet
{
    public int
        Level = 0,
        EXP = 0,
        
        HP = 0,
        HPMax = 0,
	        SP = 0,
        SPMax = 0,
	        Strength = 0,
        Speed = 0,
        Soul = 0;
	    private Dictionary <MID, Modifier> mModifiers = new Dictionary <MID, Modifier>();
	    public StatSheet()
    {
        mModifiers = new Dictionary<MID, Modifier>();
    }
	    public StatSheet(Dictionary<SID, int> newStats)
    {
        Set(newStats);
        mModifiers = new Dictionary<MID, Modifier>();
    }
	    public void Set(Dictionary<SID, int> newStats)
    {
        foreach (KeyValuePair<SID, int> stat in newStats)
        {
            this.Set(stat.Key, stat.Value);
        }
    }
	    public void Set(SID statID, int value)
    {
        switch (statID)
        {
            case SID.Level:
                Level = value;
                break;
            case SID.EXP:
                EXP = value;
                break;
	
            case SID.HP:
                HP = value;
                break;
            case SID.HP_Max:
                HPMax = value;
                break;
            case SID.SP:
                SP = value;
                break;
            case SID.SP_Max:
                SPMax = value;
                break;
	
            case SID.Strength:
                Strength = value;
                break;
            case SID.Speed:
                Speed = value;
                break;
            case SID.Soul:
                Soul = value;
                break;
            default:
                Debug.LogError("Nonexistent Stat Type Added");
                break;
	        }
    }
	    public int Get(SID statID)
    {
        switch (statID)
        {
            case SID.Level:
                return Level;
            case SID.EXP:
                return EXP;
	
            case SID.HP:
                return HP;
            case SID.HP_Max:
                return HPMax;
            case SID.SP:
                return SP;
            case SID.SP_Max:
                return SPMax;
	
            case SID.Strength:
                return Strength;
            case SID.Speed:
                return Speed;
            case SID.Soul:
                return Soul;
            default:
                Debug.LogError("StatSheet: Cannot find stat type:" + statID.ToString());
                return 0;
	        }
    }
	    public Dictionary<SID,int> Get()
    {
        Dictionary<SID, int> rawStats = new Dictionary<SID, int>();
        rawStats.Add(SID.Level, Level);
        rawStats.Add(SID.EXP, EXP);
	        rawStats.Add(SID.HP_Max, HPMax);
        rawStats.Add(SID.SP_Max, SPMax);
	        rawStats.Add(SID.Strength, Strength);
        rawStats.Add(SID.Speed, Speed);
        rawStats.Add(SID.Soul, Soul);
	        return rawStats;
	
    }
	    public void Add(SID statID, int value)
    {
        int newValue = this.Get(statID) + value;
        this.Set(statID, newValue);
    }
	    public void Add(Dictionary<SID, int> stats)
    {
        foreach (KeyValuePair<SID, int> stat in stats)
        {
            this.Add(stat.Key, stat.Value);
        }
    }
	    public Dictionary<MID, Modifier> Modifiers
    {
        get{return mModifiers;}
        set{value = mModifiers;}
    }
	    
	    public void AddModifier(MID modID, Modifier modifier)
    {
        mModifiers.Add(modID, modifier);
    }
   
    public void RemoveModifier(MID modID)
    {
        mModifiers.Remove(modID);
    }
}

You're on the right track but I'd recommend taking another step back and looking at what that class actually does. You have a list of integers and a series of functions that gets and sets the value of them based on another index. Ignoring for a moment the Dictionary of modifiers, doesn't that behavior sound just like what a Dictionary itself does? In fact, a Dictionary is just a class with methods similar to your own but the get and set operations are abstracted away in brackets and the assignment operator. Consider instead just using two Dictionaries, one for the stats and one for the modifiers.

This topic is closed to new replies.

Advertisement