Should I use Struct instead of the lightweight data class for Linq2Sql data?

I often take classes that linq2sql generates and creates a simple data-only class.

public class myentity
{
     public Guid id { get; set; }
     public string name { get; set; }
     // etc
}

      

I didn't put methods in these classes and I mostly use them as helper classes, so I can serialize / json and other similar actions easily.

My question is, should I use a struct in this case and not a class?

It seems to make sense to make it a struct as your more or less struct definition, but I don't know if the performance would be ideal here as I often pass classes from method to method and I don't know if a ton of copies are required since structs are types values.

Another thing I do quite often is using Linq2Sql latency to return my own lightweight version of the Linq2Sql classes, not the one they generate. I'm not entirely sure if using a struct instead of a class will have an adverse performance impact.

an example of how I would use deferred 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);
}

      

+2


source to share


2 answers


I would go with class

. The volatile is struct

rarely good. Unless you see a clear advantage to using structs instead of classes, you should avoid doing so.

Specifically, in your case, the usage struct

makes it difficult to modify the content of the instance (for example, deserialize the JSON and fill in some properties, you will have to use ref

all the time).



Suppose that Entity

is a structure:

List<Entity> entities = ...;
entities[0].Name = "Test"; // won't compile.

      

+7


source


I think you misunderstood the essence of structures. You say "this is more or less a structure definition" but you didn't mention value type semantics (copying) once - and that's a structure definition, IMO. It doesn't matter how many methods there are, etc. - about the semantics of a value or a reference type.



As Mehrdad says, volatile structures are rarely good. I would say that it is almost always evil and will cause strange errors that are very difficult to diagnose. Just say no - structures are very rarely the right choice in my experience. They are for basic data types like numbers, dates, symbols, enumerations, etc.

+5


source







All Articles