4

If I have a class and it's essentially just a bunch of variables - has no methods, really more of a storage space - is it better to convert it to a struct?

What is the "rule" for when to use a struct and when to use a class?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Diskdrive
  • 18,107
  • 27
  • 101
  • 167
  • possible duplicate of [When should I use a struct instead of a class?](http://stackoverflow.com/questions/85553/when-should-i-use-a-struct-instead-of-a-class) – Gishu Mar 03 '11 at 04:40
  • http://stackoverflow.com/questions/203695 could be helpful too.. – Gishu Mar 03 '11 at 04:41

6 Answers6

2

Rule number one is that it should not be larger than 16 bytes. Typically 4 fields. The jitter generated code takes a nasty nosedive when it gets larger than that. That's not compatible with "bunch of variables". There's nothing wrong with a simple class.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

My rule of thumb is when the entity represents a value (and thus is immutable) and doesn't have identity (for example, two instances of "5" are the same). Hence, you should override == as well as .Equals. String, for example, is a class only for pragmatic reasons. Similarly, don't use a struct for more than a handful of fields. Probably it could be further decomposed.

Mark Sowul
  • 10,244
  • 1
  • 45
  • 51
1

-the member and inheritance of a class is private by default while those are public in struct.

-Use a class when object identity is more important than value. Use a struct when the value contained by an instance is more important than instance identity.

-Structures are value types; classes are reference types.

-A structure must have at least one nonshared variable or event member. a class can be completely empty.

-if you need to handle event use class.

-class use heap allocation while stack use stack allocation

-if u need to initialized any member value then use class because you cant do this in stack.

i think now u can understand the differences. now u can use stack or class according to your need.

thanks arefin

stinepike
  • 54,068
  • 14
  • 92
  • 112
  • See http://msdn.microsoft.com/en-us/library/ms173121.aspx . Particularly the part that reads, "The access level for class members and struct members, including nested classes and structs, is private by default." Don't confuse C#'s (or .net's) definition of `struct` with C++'s. – cHao Mar 03 '11 at 04:44
  • 1
    Also, structs can have constructors. They just can't have *default* (parameterless) constructors. – cHao Mar 03 '11 at 04:46
1

From Effective C#

Value types or reference types? Structs or classes? When should you use each? This isn’t C++, in which you define all types as value types and can create references to them. This isn’t Java, in which everything is a reference type (unless you are one of the language designers). You must decide how all instances of your type will behave when you create it. It’s an important decision to get right the first time. You must live with the consequences of your decision because changing later can cause quite a bit of code to break in subtle ways. It’s a simple matter of choosing the struct or class keyword when you create the type, but it’s much more work to update all the clients using your type if you change it later.

It’s not as simple as preferring one over the other. The right choice depends on how you expect to use the new type. Value types are not polymorphic. They are better suited to storing the data that your application manipulates. Reference types can be polymorphic and should be used to define the behavior of your application. Consider the expected responsibilities of your new type, and from those responsibilities, decide which type to create. Structs store data. Classes define behavior.

From C# in Depth

Suppose you’re reading something fantastic, and want a friend to read it too. Let’s further suppose that it’s a document in the public domain, just to avoid any accusations of supporting copyright violation. What do you need to give your friend so that he can read it too? It depends entirely on what you’re reading.

First we’ll deal with the case where you have real paper in your hands. To give your friend a copy, you’d need to photocopy all the pages and then give it to him. At that point, he has his own complete copy of the document. In this situation, we’re dealing with value type behavior. All the information is directly in your hands—you don’t need to go anywhere else to get it. Your copy of the information is also independent of your friend’s after you’ve made the copy. You could add some notes to your pages, and his pages wouldn’t be changed at all.

Compare that with the situation where you’re reading a web page. This time, all you have to give your friend is the URL of the web page. This is reference type behavior, with the URL taking the place of the reference. In order to actually read the document, you have to navigate the reference by putting the URL in your browser and asking it to load the page. On the other hand, if the web page changes for some reason (imagine it’s a wiki page and you’ve added your notes to the page), both you and your friend will see that change the next time each of you loads the page.

The differences we’ve seen in the real world form the heart of the distinction between value types and reference types in C# and .NET. Most types in .NET are reference types, and you’re likely to create far more reference than value types. The most common cases to know are that classes (declared using class) are reference types, and structures (declared using struct) are value types. The other situations are as follows:

Array types are reference types, even if the element type is a value type (so int[] is still a reference type, even though int is a value type).

Enumerations (declared using enum) are value types.

Delegate types (declared using delegate) are reference types.

Interface types (declared using interface) are reference types, but they can be implemented by value types.

Now that we have a basic idea of what reference types and value types are about, we’ll look at a few of the most important details.

Jeff Swensen
  • 3,513
  • 28
  • 52
0

See... this msdn article

Structs vs. Classes

Structs may seem similar to classes, but there are important differences that you should be aware of. First of all, classes are reference types and structs are value types. By using structs, you can create objects that behave like the built-in types and enjoy their benefits as well.

Heap or Stack?

When you call the New operator on a class, it will be allocated on the heap. However, when you instantiate a struct, it gets created on the stack. This will yield performance gains. Also, you will not be dealing with references to an instance of a struct as you would with classes. You will be working directly with the struct instance. Because of this, when passing a struct to a method, it's passed by value instead of as a reference.

So if you are using the data only in a method and are not passing it around to functions then a struct can give you performance gains as it is only allocated on the stack... if you are going to pass it around to a bunch of function then a class is probably better because it would be passed around by reference and not "copied" over and over...

John Sobolewski
  • 4,512
  • 1
  • 20
  • 26
  • 3
    It is a misleading article. Better is to look at Eric Lippert's blog post: http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx. The fact that it's heap or stack is *not* what you should focus on with struct/class, it's pass-by-value or pass-by-reference. – Mark Sowul Mar 03 '11 at 04:25
  • value type = on stack... reference type = on heap... struct is on the stack.. and therefore a value type... and therefore passed by value... ok not really a rule as asked for but I though getting at the actual reasons might help... – John Sobolewski Mar 03 '11 at 05:40
  • I read the article and now understand what you are talking about. We should focus on semantic meaning of struct vs class not the implementation. – John Sobolewski Mar 03 '11 at 06:00
0

Structs are generally used for small amounts of data that represent a single, cohesive unit of information. They're usually passed around by value, which involves passing a copy of it rather than a reference to the object itself.

This means that structs have a couple of minor gotchas. If

  • the data will have value semantics -- that is, if the object could be cloned without causing issues, and what matters is the values and not their identities;
  • the total amount of data will be less than about 16 bytes, since the runtime will end up copying it around rather than just passing a reference; and
  • if it's immutable, since modifying a copy generally won't modify the original;

then you may do well to use a struct.

If any of those aren't true, you may want to consider keeping the class as a class.

cHao
  • 84,970
  • 20
  • 145
  • 172
  • @Mark So you couldn't `Foo(ref myStruct);` ? – Jeff Swensen Mar 03 '11 at 04:46
  • @Mark: `public void NotAlways(ref PassedByReference example)`. – cHao Mar 03 '11 at 04:50
  • 16 bytes of data? isn't that quite small? like 4 integers? – Diskdrive Mar 03 '11 at 04:56
  • @Robo: Yes, it's pretty small. You don't want to have much in a struct, as the runtime copies all those bytes whenever it passes the struct to a method. Past 16 bytes or so, that gets to be a lot of copying, making structs less suitable. – cHao Mar 03 '11 at 05:05