03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

270 ❘ CHAPTER 12 Classes and Structures<br />

contains methods for manipulating the recipe, so you don’t need to write a separate module containing<br />

methods to convert measurements, scale the recipe, and print. The class keeps all these<br />

things together, so they’re easy to find.<br />

This chapter explains how to define and instantiate classes and structures. It explains the key<br />

differences between classes and structures and provides some recommendations about which to<br />

use under different circumstances.<br />

Classes and structures provide almost exactly the same features. For example, both can have properties,<br />

methods, and events. The following sections start by describing classes. As you read about classes, be<br />

aware that most of those features also apply to structures. Sections later in the chapter explain where<br />

the two differ.<br />

Classes<br />

A class packages data and related behavior. The Recipe class described earlier is an example.<br />

It contains information about a recipe and methods for manipulating its data.<br />

Here’s the syntax for declaring a class.<br />

«attributes» «accessibility» «abstract|sealed|static» «partial»<br />

class name «inheritance»<br />

{<br />

statements<br />

}<br />

The only thing all class declarations require is the class clause (including the class’s name). Everything<br />

else is optional. The following code describes a valid (albeit not very interesting) class.<br />

class Person<br />

{<br />

}<br />

The following sections describe the pieces of the general declaration in detail.<br />

attributes<br />

The optional attributes section is a list of attributes that apply to the class. An attribute further refines<br />

the definition of a class to give more information to the compiler and the runtime system.<br />

Attributes are rather specialized and address issues that arise when you perform specific programming<br />

tasks. For example, if you need to copy instances of the class from one application to another,<br />

you can mark the class with the Serializable attribute. This isn’t something you need to do for<br />

every class. Actually, some attributes are so specialized that you may never use them.<br />

Because attributes are so specialized, they are not described in detail here. (Although Chapter 25,<br />

“Serialization,” says more about serialization.) For more information, consult the Internet and the<br />

online help.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!