1

I have a struct like this.

public struct MyStruct
{
    public string name;
    // other variables and stuff

    public MyStruct(string name)
    {
        this.name = name;
    }
}

I'm storing many, possibly hundreds or even thousands of those in a dictionary with their names as keys.

var myStructs = new Dictionary<string, MyStruct>();
myStructs.Add("Foo", new MyStruct("Foo"));

I don't always have access to the dictionary's keys (such as when retrieving values) so the names of the structs have to be defined in them.

My problem is, the structs can have different names than their keys in the dictionary. Is it an actual problem to have such a condition exist?

myStructs.Add("Bar", new MyStruct("Baz"));

This is a bit of off-topic on this question yet kind-of relevant to the problem above, but if the name of a struct under the key Foo is changed, how would I update the key to the new name?

var temp = myStructs["Foo"];
temp.name = "Bar";
myStructs["Foo"] = temp;
Spans
  • 364
  • 7
  • 17

2 Answers2

3

I think you need a unique ID and a DisplayName in MySctuct. If you save records in a database having a unique would be a better option. And actually a List<MyStruct> will provide you the same functionality in this case and you don't have to bother about changing the Dictionary key.

As per MSDN, you should use a Class in your case.

Choosing Between Class and Struct

√ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

X AVOID defining a struct unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).

  • It has an instance size under 16 bytes.

  • It is immutable.

  • It will not have to be boxed frequently.
CharithJ
  • 46,289
  • 20
  • 116
  • 131
  • I'll go with a list and some LINQ magic to find the values based on a given name. Also, Microsoft itself is violating the guidelines they've set. Not that I mean to completely ignore them, I just don't feel like forcing myself to follow them. – Spans Jul 23 '15 at 21:45
0
var temp = myStructs["Foo"];
myStructs.Remove(temp.name);
temp.name = "Bar";
myStructs.Add(temp.name, temp);

Alternatively, you can make MyStruct.name into a property, and automatically update whenever the name changes:

struct MyStruct
{
    private string _name;
    public string name
    {
        get { return _name; }
        set
        { 
            if (_name == value) return;
            GlobalStorageClass.myStructs.Remove(_name);
            _name = value;
            GlobalStorageClass.myStructs.Add(_name, this);
        }
    }

    public MyStruct(string name)
    {
        _name = name;
        GlobalStorageClass.myStructs.Add(name, this);
    }
}

Where GlobalStorageClass.myStructs is the dictionary.

Jashaszun
  • 9,207
  • 3
  • 29
  • 57