- Introduction
- Struct types
- Primitive types
- Enumeration types
-
The value types
are the
struct types,
primitive types
and enumeration types.
-
The declaration of a struct type is similar to that of a class
type.
-
For example,
it can declare fields, constructors and
methods.
-
However, the big difference is:
a variable
that is of some class type
points to an object of that class
whereas a variable
that is of some struct type
stores the value itself.
-
So assignment between two structs causes copying
of a struct value to take place
rather than making a variable point to the same object
as some other variable.
-
The other big difference is that a struct variable is stored on the
stack (or is inline) whereas a class object is stored on the heap.
Here is an example of a struct type coded in C#:
public struct SPoint
{
private int iX;
private int iY;
public SPoint(int pX, int pY)
{
iX = pX;
iY = pY;
}
public override string ToString()
{
return iX + ":" + iY;
}
}
Here is a method that uses this struct type:
using System;
public class SPointTest
{
public static void Main()
{
SPoint tSPoint = new SPoint(100, 200);
Console.WriteLine(tSPoint);
SPoint tAnotherSPoint = tSPoint;
Console.WriteLine(tAnotherSPoint);
}
}
-
You cannot extend struct types
(e.g., to produce NamedSPoint).
-
Use structs for lightweight objects.
In C#, each primitive type is just an alias for a struct type.
|
size
|
C#
|
System.Boolean
|
8
|
bool
|
System.Byte
|
8
|
byte
|
System.Int16
|
16
|
short
|
System.Int32
|
32
|
int
|
System.Int64
|
64
|
long
|
System.Single
|
32
|
float
|
System.Double
|
64
|
double
|
System.Char
|
16
|
char
|
System.Decimal
|
128
|
decimal
|
-
C# also has
enumeration types.
-
Here is an example:
enum Days : int
{
Sunday = 1,
Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday
}
-
Each enum declaration introduces a new type.