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.

Classes ❘ 273<br />

Extension Tension<br />

You can add an extension method to a class even if it is declared sealed. If you add<br />

features that don’t match the class’s original purpose, you can make the class more<br />

confusing and harder to use correctly. Adding new features to a sealed class also<br />

violates the idea that the class is in some sense “finished.” To avoid confusion, don’t<br />

add extension methods to a sealed class unless you must.<br />

For more information on extension methods, see the section “Extension Methods”<br />

in Chapter 6, “Methods.”<br />

partial<br />

The partial keyword tells <strong>C#</strong> that the current declaration defines only part of the class. The following<br />

code shows the Person class broken into two pieces.<br />

partial class Person<br />

{<br />

public string FirstName, LastName;<br />

}<br />

partial class Person<br />

{<br />

public string Street, City, State, Zip;<br />

}<br />

You can break a class into any number of pieces. (If you do break a class into pieces, all of them<br />

must include the partial keyword.) At compile time, <strong>C#</strong> finds the pieces and combines them to<br />

define the class.<br />

Normally, you wouldn’t break a class into pieces within a single module. In fact, it’s not a good idea to<br />

break a class into pieces unless you must. Keeping all the class’s code in one piece makes it easier to find.<br />

Picking Up the Pieces<br />

The reason partial classes were introduced was to hide automatically generated<br />

code from developers.<br />

For example, when you create a form in a Windows Forms application, the project<br />

contains a lot of code to create and initialize the form’s controls. That code is confusing,<br />

and if you modify it, you can break the form so that it won’t work anymore.<br />

To help protect that code from accidental breakage, Visual Studio places it in a<br />

separate module with a name similar to Form1.Designer.cs. Any code you add to<br />

the form goes into the similarly named file Form1.cs. The partial keyword lets<br />

both of these pieces of code help define the Form1 class.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!