Should I use a Struct instead of a lightweight data class for my Linq2Sql data?
-
06-07-2019 - |
Question
I often take the classes that linq2sql generates and create a simple data-only class like so
public class myentity
{
public Guid id { get; set; }
public string name { get; set; }
// etc
}
I don't put methods in these classes and I mainly use them as helper classes so I can serialize to/from json and other similar actions, quite easily.
My question is, should I use a struct in this case rather than a class?
It seems to make sense to make it a struct as its more or less the definition of a struct, but I dont know if the performance will be ideal here since I often pass the classes around from method to method and I don't want a ton of copies since structs are value types.
Another thing I do quite often is use Linq2Sql's delayed execution to return my own lightweight version of the Linq2Sql classes, rather than the one they generate. I'm not entirely sure if using a struct instead of a class would have some adverse performance impact here.
an example of how I'd use delayed execution is something like this
public IEnumerable<myentity> getEntities()
{
return from me in MyEntity return new myentity() { id = me.id, name = me.name };
}
public IEnumerable<myentity> getEntitiesThatStartWith(string s)
{
return from me in getEntities() where me.name.StartsWith(s);
}
Solution
I'd go with a class
. A mutable struct
is rarely a good thing. If you don't see a clear advantage of using structs instead of classes, you should avoid it.
Specifically, in your case, using a struct
makes it harder for a method to modify contents of an instance (e.g. deserialize from JSON and fill some properties; you'd have to use ref
all the time).
Assume Entity
is a struct:
List<Entity> entities = ...;
entities[0].Name = "Test"; // won't compile.
OTHER TIPS
I think you've misunderstood the point of structs. You say "it's more or less the definition of a struct" but you haven't mentioned value type semantics (copying) once - and that's the definition of a struct, IMO. It doesn't matter how many methods there are, etc - it's about the value or reference type semantics.
As Mehrdad says, mutable structs are rarely a good thing. I'd put it more strongly: they're almost always evil, and will cause weird bugs which are very hard to diagnose. Just say no - structs are very rarely the right choice in my experience. They're for fundamental data types like numbers, dates, characters, enums etc.