Classes and Structs C# Help

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 on 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
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 their 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 Phone Customer instances to be allocated on the stack instead of the managed heap,
you could write:

struct PhoneCustomerStruct
public const string DayOfSendingBill
•• 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:

In most’ cases, you’ll use classes much more often than structs. Therefore, we discuss classes first and then 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.

Posted on October 28, 2015 in Objects and Types

Share the Story

Back to Top
Share This