4

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

4

5 Answers 5

4

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.
Sign up to request clarification or add additional context in comments.

Comments

1

Use a class unless you've got very specific reasons to use a struct. See 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 Is there a way to require that an argument provided to a method is not null?

Comments

0

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. 

Comments

0

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!!!

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.