I n t e r f a c e s , S t r u c t u r e s , a n d E n u m e r a t i o n s
are still separate and distinct. That is,
’s value. This would not be the case
were class references. For example, here is the
// Use a class.
// Now a class.
// Now show a class object assignment.
330
P a r t I :
T h e C # L a n g u a g e
Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x);
}
}
The output from this version is shown here:
a.x 10, b.x 20
a.x 30, b.x 30
As you can see, after the assignment of
b
to
a
, both variables refer to the same object—the
one originally referred to by
b
.
Why Structures?
At this point, you might be wondering why C# includes the
struct
since it seems to be a
less-capable version of a
class
. The answer lies in efficiency and performance. Because
structures are value types, they are operated on directly rather than through a reference.
Thus, a
struct
does not require a separate reference variable. This means that less memory
is used in some cases. Furthermore, because a
struct
is accessed directly, it does not suffer
from the performance loss that is inherent in accessing a class object. Because classes are
reference types, all access to class objects is through a reference. This indirection adds
overhead to every access. Structures do not incur this overhead. In general, if you need
to simply store a group of related data, but don’t need inheritance and don’t need to operate
on that data through a reference, then a
struct
can be a more efficient choice.
Here is another example that shows how a structure might be used in practice. It
simulates an e-commerce transaction record. Each transaction includes a packet header that
contains the packet number and the length of the packet. This is followed by the account
number and the amount of the transaction. Because the packet header is a self-contained
unit of information, it is organized as a structure. This structure can then be used to create
a transaction record, or any other type of information packet.
// Structures are good when grouping small amounts of data.
using System;
// Define a packet structure.
struct PacketHeader {
public uint PackNum; // packet number
public ushort PackLen; // length of packet
}
// Use PacketHeader to create an e-commerce transaction record.
class Transaction {
static uint transacNum = 0;
PacketHeader ph; // incorporate PacketHeader into Transaction
string accountNum;
double amount;
www.freepdf-books.com