tags:

views:

162

answers:

5

Duplicate: When should I use a structure instead of a class?

Just wondering if anyone can provide some advice or examples of when it is best to use a structure over a class in .NET or vice versa

I have done some background reading and understand the differences between two, ie structures are stored on the stack, classes on the heap ect. But havent been able to find some clear examples where one would provide a benefit over the other.

Many Thanks

+1  A: 

Use a class unless you've got very specific reasons to use a struct. See http://stackoverflow.com/questions/667285/questions-about-structs for some of the specific reasons.

Edit: One of the possible advantages to a struct over a class is that you can't ever have null instances. See http://stackoverflow.com/questions/754330/is-there-a-way-to-require-that-an-argument-provided-to-a-method-is-not-null/

Dan
A: 

I prefer Classes.

Structure TestStruct
    Dim Name as String
End Structure

Dim x as TestStruct

If x Is Nothing Then 
'ALWAYS returns false. A class would return true. Nullability, baby.
Josh Stodola
A: 

I found this page for you. It explains where to use one or the other, the benefits and drawbacks of each one.

http://www.jaggersoft.com/pubs/StructsVsClasses.htm

Regards!!!

MRFerocius
A: 

Very basic guideline, and not even .NET specific:

Use CLASS for everything except when you need very small, very simple container. if you don't want properties nor functions, you should use a class.

a good example in my opinion for a struct is when you need to make an array of items, but the items is a "pair" of int and string. something basic like that

csmba
+3  A: 

To quote a good answer to the same question (When should I use a struct instead of a class?):

MSDN has the answer: Choosing Between Classes and Structures.

Basically, that page gives you a 4-item checklist and says to use a class unless your type meets all of the criteria.

Do not define a structure unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (integer, double, and so on).
  • It has an instance size smaller than 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.
Daniel LeCheminant