Answer the question
In order to leave comments, you need to log in
How to properly store c# structure?
Good afternoon. The question of the organization of memory and how it is generally more correct to do it. So, there is some data structure
public struct myStruct
{
public myEnum id;
public string field1;
public string field2;
public List<string> fields3;
}
public static myStruct Get(myEnum id)
{
switch (id)
{
case myEnum.First: return new myStruct(. . . );
case myEnum.Second: return new myStruct(. . . );
default: return null;
}
}
//вызываем так
var result = Get(myEnum.first);
public static class pogreb
{
public static Dictionary<myEnum, myStruct> spravochnik;
public static void fillSpravochnik()
{
var res = new Dictionary<myEnum, myStruct>();
res.Add( myEnum.first, new myStruct(. . .) );
res.Add( myEnum.second, new myStruct(. . .) );
spravochnik = res;
}
}
//Ну и вызывать, соответственно
if(pogreb.spravochnik == null) pogreb.fillSpravochnik();
var result = pogreb.ContainsKey(myEnum.first) ? pogreb[myEnum.first] : null;
Answer the question
In order to leave comments, you need to log in
Looks like a "hardcode vs container" comparison. The difference is obvious: Dictionary
it provides search with complexity O(1)
(against O(n)
the switch) and is able to expand dynamically.
In the context of the task, it is like DI for the poor. In this case, the Dictionary will be clearer.
It would not be superfluous to read the style guide for C #
Since we are talking about structures, the second option does not make sense, because. copies of the structures stored in the dictionary will still be returned from the dictionary: in C#, structures are value types.
Well, for the future: if we go the second way, then we need to use encapsulation more actively. Those. initialization of the spravochnik field and getting a value from it must be done directly in the pogreb class . Outside, the class should expose not a public field (public fields are almost always evil), but a method or property that will check / initialize sparovochnik and look for a value in it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question