Classes and Structs
Classes and structs are essentially templates from which you can
create objects. Each object contains data and has methods to manipulate and
access that data. The class defines what data and functionality each particular
object (called an instance) of that class can contain. For
example, if you have a class that represents a customer, it might define fields
such as CustomerID, FirstName,
LastName, and Address, which
you will use to hold information about a particular customer. It might also
define functionality that acts upon the data stored in these fields. You can
then instantiate an object of this class to represent one specific customer, set
the field values for that instance, and use its functionality.
class PhoneCustomer
{
public const string DayOfSendingBill = "Monday";
public int CustomerID;
public string FirstName;
public string LastName;
}
Structs differ from classes in the way that they are stored in
memory and accessed (classes are reference types stored in the heap, structs are
value types stored on the stack), and in some of the features (for example,
structs don’t support inheritance). You will tend to use structs for smaller
data types for performance reasons. In terms of syntax, however, structs look
very similar to classes; the main difference is that you use the keyword struct instead of class to declare
them. For example, if you wanted all PhoneCustomer
instances to be allocated on the stack instead of the managed heap, you could
write:
struct PhoneCustomerStruct
{
public const string DayOfSendingBill = "Monday";
public int CustomerID;
public string FirstName;
public string LastName;
}
For both classes and structs, you use the keyword new to declare an instance: This keyword creates the object
and initializes it; in the following example, the default behavior is to zero
out its fields:
PhoneCustomer myCustomer = new PhoneCustomer(); // works for a class
PhoneCustomerStruct myCustomer2 = new PhoneCustomerStruct();// works for a struct
In most cases, you’ll find you use classes much more often
than structs. For this reason, this chapter discusses classes first, and then
points out the differences between classes and structs and the specific reasons
why you might choose to use a struct instead of a class. Unless otherwise
stated, however, you can assume that code presented for a class will work
equally well for a struct.
If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates.
Subscribe Now!
0 comments: