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.

42 ❘ CHAPTER 3 Program and Code File Structure<br />

If you change the project’s default namespace, any classes that you create in the future are placed in<br />

the new namespace.<br />

Class Definitions<br />

The WindowsFormsApplication1 example program shown earlier included the following<br />

class definition.<br />

public partial class Form1 : Form<br />

{<br />

public Form1()<br />

{<br />

InitializeComponent();<br />

}<br />

}<br />

Chapter 12 has a lot more to say about classes. For now you should know that all classes (and<br />

structures, enumerations, and other program elements) must be declared inside some namespace.<br />

One last fact about classes is worth mentioning here during the discussion of program and code file<br />

structure. If you look at the previous class definition, you see that it includes the partial keyword.<br />

That keyword means that this is only part of the class’s definition and that other class statements<br />

may contain more pieces of the class.<br />

TIP Usually a code file includes a single namespace and that defines some or<br />

all of a single primary class. The namespace may also include helper structures,<br />

classes, and other elements used by the primary class. You can define as many<br />

namespaces and classes as you like in a single file, but then managing the file<br />

becomes harder.<br />

If you use the Project menu’s Add Class and other commands to create new<br />

classes, you’ll get one class per file.<br />

In this example, the form’s controls are defined in the file Form1.Desginer.cs. If you look at that file,<br />

you can see the following code (with some code omitted).<br />

namespace WindowsFormsApplication1<br />

{<br />

partial class Form1<br />

{<br />

... Code omitted ...<br />

}<br />

}<br />

This code begins with the same namespace statement used in the file Form1.cs. That means the code<br />

in this file is in the same namespace as the code in the other file.<br />

Inside the namespace statement is a partial class statement that adds more code to the Form1 class.<br />

If a class is split into multiple pieces, then all the pieces must use the partial keyword. That means<br />

if you see a class declared with that keyword, you know there are other pieces somewhere.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!