Information Technology Reference
In-Depth Information
What Are Structs?
Structs are programmer-defined data types, very similar to classes. They have data members
and function members. Although similar to classes, there are a number of important differ-
ences. The most important ones are the following:
Classes are reference types and structs are value types.
￿
Structs are implicitly sealed, which means that they cannot be derived from.
The syntax for declaring a struct is similar to that of declaring a class.
Keyword
struct StructName
{
MemberDeclarations
}
For example, the following code declares a struct named Point . It has two public fields,
named X and Y . In Main , three variables of the struct type Point are declared, and their values
are assigned and printed out.
struct Point
{
public int X;
public int Y;
}
class Program
{
static void Main()
{
Point First, Second, Third;
First.X = 10; First.Y = 10;
Second.X = 20; Second.Y = 20;
Third.X = First.X + Second.X;
Third.Y = First.Y + Second.Y;
Console.WriteLine("First: {0}, {1}", First.X, First.Y);
Console.WriteLine("Second: {0}, {1}", Second.X, Second.Y);
Console.WriteLine("Third: {0}, {1}", Third.X, Third.Y);
}
}
Search WWH ::




Custom Search