Home > Articles > Programming > C#

Designing C# Objects Using Classes

The real power of leveraging objects comes from being able to design and implement custom objects of your own design. In this lesson you'll learn how to create your own objects (i.e. object-oriented programming) by using classes. You'll learn how to define the template for an object and how to create your own custom properties and methods.
This chapter is from the book

This chapter is from the book

You learned about what makes an object an object in Hour 3, "Understanding Objects and Collections." Since that hour, you've learned how to manipulate objects such as forms and controls. The real power of leveraging objects comes from being able to design and implement custom objects of your own design. In this hour, you'll learn how to create your own objects by using classes (in contrast to using static methods). You'll learn how to define the template for an object and how to create your own custom properties and methods.

The highlights of this hour include the following:

  • Encapsulating data and code using classes

  • Comparing instance member classes with static member classes

  • Constructors and destructors

  • Creating an object interface

  • Exposing object attributes as properties

  • Exposing methods

  • Instantiating objects from classes

  • Binding an object reference to a variable

  • Understanding object lifetime

  • Releasing object references


There is simply no way to become an expert on programming classes in a single hour. However, when you've finished with this hour, you'll have a working knowledge of creating classes and deriving custom objects from those classes; consider this hour a primer on object-oriented programming. I strongly encourage you to seek other texts that focus on object-oriented programming after you feel comfortable with the material presented throughout this book.

Understanding Classes

Classes enable you to develop applications using object-oriented programming (OOP) techniques (recall that I discussed OOP briefly in Hour 3). Classes are templates that define objects. Although you may not have known it, you have been programming with classes throughout this book. When you create a new form in a C# project, you are actually creating a class that defines a form; forms instantiated at runtime are derived from the class. Using objects derived from predefined classes, such as a C# Form class, is just the start of enjoying the benefits of object-oriented programming—to truly realize the benefits of OOP, you must create your own classes.

The philosophy of programming with classes is considerably different from that of "traditional" programming. Proper class-programming techniques can make your programs better, both in structure and in reliability. Class programming forces you to consider the logistics of your code and data more thoroughly, causing you to create more reusable and extensible object-based code.

Encapsulating Data and Code Using Classes

An object derived from a class is an encapsulation of data and code; that is, the object comprises its code and all the data it uses. For example, suppose that you need to keep track of employees in an organization and that you need to store many of pieces of information for each employee, such as Name, Date Hired, and Title. In addition, suppose you need methods for adding and removing employees, and you want all this information and functionality available to many functions within your application. You could use static methods to manipulate the data. However, this would most likely require many variable arrays, as well as code to manage the arrays.

A better approach is to encapsulate all the employee data and functionality (adding and deleting routines and so forth) into a single, reusable object. Encapsulation is the process of integrating data and code into one entity—an object. Your application, as well as external applications, could then work with the employee data through a consistent interface—the Employee object's interface (An interface is a set of exposed functionality—essentially, code routines.)


Creating objects for use outside of your application is beyond the scope of this book. The techniques you'll learn in this hour, however, are directly applicable to creating externally creatable objects.

The encapsulation of data and code is the key detail of classes. By encapsulating the data and the routines to manipulate the data into a single object by way of a class, you free application code that needs to manipulate the data from the intricacies of data maintenance. For example, suppose company policy has changed so that when a new employee is added to the system, a special tax record needs to be generated and a form needs to be printed. If the data and code routines weren't encapsulated in a common object but were written in various places throughout your code, you would need to modify each and every module that contained code to create a new employee record. By using a class to create an object, you need to change only the code in one location: within the object. As long as you don't modify the interface of the object (discussed shortly), all the routines that use the object to create a new employee will instantly have the policy change in effect.

Comparing Instance Members with Static Members

You learned in Hour 11, "Creating and Calling Methods," that C# does not support global methods, but supports only class methods. By creating static methods, you create methods that can be accessed from anywhere in the project through the class.

Instance methods are similar to static methods in how they appear in the C# design environment and in the way in which you write code within them. However, the behavior of classes at runtime differs greatly from that of static members. With static members, all static data is shared by all members of the class. In addition, there are never multiple instances of the static class data. With instance member classes, objects are instantiated from a class and each object receives its own set of data. Static methods are accessed through the class, whereas nonstatic methods (also called instance methods) are accessed through instances of the class.

Instance methods differ from static methods in more ways than just in how their data behaves. When you define a static method, it is instantly available to other classes within your application. However, instant member classes aren't immediately available in code. Classes are templates for objects. At runtime, your code doesn't interact with the code in the class per se, but it instantiates objects derived from the class. Each object acts as its own class "module" and thus it has its own set of data. When classes are exposed externally to other applications, the application containing the class's code is called the server. Applications that create and use instances of objects are called clients. When you use instances of classes in the application that contains those classes, the application itself acts as both a client and a server. In this hour, I'll refer to the code instantiating an object derived from a class as client code.

Begin by creating a new Windows Application titled Class Programming Example. Change the name of the default form to fclsClassExample and set its Text property to Class Example. Next, change the entry point of the project in the method Main() to reference fclsClassExample instead of Form1. Add a new class to the project by choosing Add Class from the Project menu. Save the class with the name clsMyClass.cs (see Figure 17.1).

Figure 17.1 Classes are added to a project the same as other object files are added.

Constructors and Destructors

As you open your new class file, you'll notice that C# added the public class declaration and a method called clsMyClass(). This is known as the class constructor. A constructor has the same name as the class, includes no return type, and has no return value. A class constructor is called whenever a class object is instantiated. Therefore, it's normally used for initialization if some code needs to be executed automatically when a class is instantiated. If a constructor isn't specified in your class definition, the Common Language Runtime (CLR) will provide a default constructor.


Objects consume system resources. The .NET Framework (discussed in Hour 24, "The 10,000-Foot View") has a built-in mechanism to free resources used by objects. This mechanism is called the Garbage Collector (and it is discussed in Hour 24 as well). Essentially, the garbage collector determines when an object is no longer being used and then destroys the object. When the garbage collector destroys an object, it calls the object's destructor method. If you aren't careful about how to implement a destructor method, you can cause problems. I recommend that you seek a book dedicated to object-oriented programming to learn more about constructors and destructors.

Creating an Object Interface

For an object to be created from a class, the class must expose an interface. As I mentioned earlier, an interface is a set of exposed functionality (essentially, code routines/methods). Interfaces are the means by which client code communicates with the object derived from the class. Some classes expose a limited interface, whereas some expose complex interfaces. The content and quantity of your class's interface is entirely up to you.

The interface of a class consists of one or more of the following members:

  • Properties

  • Methods

  • Events

For example, assume that you are creating an Employee object (that is, a class used to derive employee objects). You must first decide how you want client code to interact with your object. You'll want to consider both the data contained within the object and the functions the object can perform. You might want client code to be able to retrieve the name of an employee and other information such as sex, age, and the date of hire. For client code to get these values from the object, the object must expose an interface member for each of the items. Recall from Hour 3 that values exposed by an object are called properties. Therefore, each piece of data discussed here would have to be exposed as a property of the Employee object.

In addition to properties, you can expose functions—such as a Delete or AddNew function. These functions may be simple in nature or very complex. The Delete function of the Employee object, for example, might be quite complex. It would need to perform all the actions necessary to delete an employee, including such things as removing the employee from an assigned department, notifying accounting to remove the employee from the payroll, notifying security to revoke the employee's security access, and so on. Publicly exposed functions of an object, as you should remember from Hour 3, are called methods.

Properties and methods are the most commonly used interface members. Although designing properties and methods may be new to you, by now using them isn't; you've been using properties and methods in almost every hour so far. Here, you're going to learn the techniques for creating properties and methods for your own objects.

For even more interaction between the client and the object, you can expose custom events. Custom object events are similar to the events of a form or a text box. However, with custom events you have complete control over the following:

  • The name of the event

  • The parameters passed to the event

  • When the event occurs


Events in C# are based on delegates. Creating custom events is complicated, and I'll be covering only custom properties and methods in this hour.

Properties, methods, and events together make up an object's interface. This interface acts as a contract between the client application and the object. Any and all communication between the client and the object must transpire through this interface (see Figure 17.2).

Figure 17.2 Clients interact with an object via the object's interface.

The technical details of the interaction between the client and the object by way of the interface are, mercifully, handled by C#. Your responsibility is to define the properties, methods, and events of an object so that its interface is logical, consistent, and exposes all the functionality a client needs to use the object.

Exposing Object Attributes as Properties

Properties are the attributes of objects. Properties can be read-only, or they can allow both reading and writing of their values. For example, you may want to let a client retrieve the value of a property containing the path of the component, but not let the client change it because you can't change the path of a running component.

You can add properties to a class in two ways. The first is to declare public variables. Any variable declared as public instantly becomes a property of the class (technically, it's referred to as a field). For example, suppose you have the following statement in the Declarations section of a class:

public long Quantity;

Clients could read from and write to the property using code such as the following:

objMyObject.Quantity = 139;

This works, but significant limitations exist that make this approach less than desirable:

  • You can't execute code when a property value changes. For example, what if you wanted to write the quantity change to a database? Because the client application can access the variable directly, you have no way of knowing when the value of the variable changes.

  • You can't prevent client code from changing a property, because the client code accesses the variable directly.

  • Perhaps the biggest problem is this: How do you control data validation? For instance, how could you ensure that Quantity was never set to a negative value?

You simply can't work around these issues using a public variable. Instead of exposing public variables, you should create class properties using property procedures.

Property procedures enable you to execute code when a property is changed, to validate property values, and to dictate whether a property is read-only, write-only, or both readable and writable. Declaring a property procedure is similar to declaring a method, but with some important differences. The basic structure of a property looks like this:

Private int privatevalue;

public int propertyname
   return privatevalue;  // Code to return the property's value .
   privatevalue = value; // Code that accepts a new value.

The first word in the property declaration simply designates the scope of the property (public or private). Properties declared with public are available to code outside of the class (they can be accessed by client code). Properties declared as private are available only to code within the class. Immediately following public or private are the data type and property name.

Place your cursor after the left bracket following the statement public class clsMyclass and press Enter to create a new line. Type the following statements into your class:

private int m_intHeight;

public int Height

You might be wondering why you just created a module-level variable of the same name as your property procedure (with a naming prefix, of course). After all, I just finished preaching about the problems of using a module-level variable as a property. A property has to get its value from somewhere, and a module-level variable is usually the best place to store it. The property procedure will act as a wrapper for this variable. Notice here that the variable is private rather than public. This means that no code outside of the class can view or modify the contents of this variable; as far as client code is concerned, this variable doesn't exist.

Between the property declaration statement and its closing brace are two constructs: the get construct and a set construct. Each of these constructs is discussed in its own section.

Creating Readable Properties Using the get Accessor

The get accessor is used to place code that returns a value for the property when read by the client. If you remove the get accessor and its corresponding brackets, clients won't be able to read the value of the property. It's rare that you'll want to create such a property, but you can.

Think of the get accessor as a method; whatever you return as the result of the method becomes the property value. Add the following statement between the get brackets:

return m_intHeight;

You return the value of the property by using the return keyword followed by the value.

Creating Writable Properties Using the set Accessor

The set accessor is where you place code that accepts a new property value from client code. If you remove the set accessor (and its corresponding brackets), clients won't be able to change the value of the property. Leaving the get accessor and removing the set accessor creates a read-only property; clients can retrieve the value of the property but they cannot change it.

Add the following statement between the set brackets:

m_intHeight = value;

The set clause uses a special variable called value, which is provided automatically by C# and always contains the value being passed to the property by the client code. The statement you just entered assigns the new value to the module-level variable.

As you can see, the property method is a wrapper around the module-level variable. When the client code sets the property, the set accessor stores the new value in the variable. When the client retrieves the value of the property, the get accessor returns the value in the module-level variable.

So far, the property code, with its get and set accessor, doesn't do anything different from what it would do if you were to simply declare a public variable (only the property procedure requires much more code). However, look at this variation of the same set accessor:

if (value >=10)
  m_intHeight = value;

This set accessor restricts the client to setting the Height property to a value greater than 10. If a value less than 10 is passed to the property, the property procedure is exited without setting m_intHeight. You're not limited to performing only data validation; you can pretty much add whatever code you desire and even call other methods. Go ahead and add the verification statement to your code so that the set accessor looks like this one. Your code should now look like the procedure shown in Figure 17.3.

Figure 17.3 This is a property procedure, complete with data validation.

Exposing Functions as Methods

Unlike a property that acts as an object attribute, methods are functions exposed by an object. A method can return a value, but it doesn't have to. Create the following method in your class now. Enter this code on the line following the closing bracket for the declared public int Height property:

public long AddTwoNumbers(int intNumber1, int intNumber2)
  return intNumber1 + intNumber2;

Recall that methods defined with a data-type return values, whereas methods defined with void don't. To make a method private to the class and therefore invisible to client code, declare the method as private rather than public.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020