2

Possible Duplicate:
When to use struct in C#?

I'm reading a C# tutorial in the net http://www.csharp-station.com/Tutorials/Lesson12.aspx.
And I came to the topic about Structs.

I'm just confused about this thing.
When does struct is advantageous to use or what are the practical uses of this?

Community
  • 1
  • 1
yonan2236
  • 13,371
  • 33
  • 95
  • 141

3 Answers3

5

Struct is a value type. Class is an object type.

You use value types when you never have to pass it by reference into a function/method parameter -- i.e. you can't change it inside of a function/method.

Whenever you pass it into a function/method, it always gets copied (i.e. pass by value), never by refernce. Structs are automatically boxed when being accessed like an object.

In practice, structs are used to model whenever you have a chunk of data that form a coherent whole (e.g. Color with RGB, vectors with XYZ, complex numbers etc.) and the whole item forms a single unit.

They are also used a lot to interface with unmanaged libraries (e.g. C or C++ DLL functions that accept struct parameters).

Stephen Chung
  • 14,497
  • 1
  • 35
  • 48
2

citation from MSDN:

The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object. In this case, the struct is less expensive.

jing
  • 1,919
  • 2
  • 20
  • 39
0

You know how ints and floats don't need to be "initialised" (set to new int/float)?

A struct is a way of declared an arrangment of members like in a class, that behave like that.

deek0146
  • 962
  • 6
  • 20