03.11.2016 Views

Beginning ASP.NET 4.5 in CSharp and VB Opsylum

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Organiz<strong>in</strong>g Code x 185<br />

It’s also easy to create your own namespaces. As long as they don’t collide with an exist<strong>in</strong>g name,<br />

you can pretty much make up your own namespaces as you see fit. For example, you could wrap the<br />

Calculator class <strong>in</strong> the follow<strong>in</strong>g namespace (<strong>in</strong> Calculator.vb or Calculator.cs <strong>in</strong> App_Code):<br />

<strong>VB</strong>.<strong>NET</strong><br />

Namespace Wrox.Samples<br />

Public Class Calculator<br />

...<br />

End Class<br />

End Namespace<br />

C#<br />

namespace Wrox.Samples<br />

{<br />

public class Calculator<br />

{<br />

...<br />

}<br />

}<br />

With the calculator wrapped <strong>in</strong> this namespace, you could create a new <strong>in</strong>stance of it like this:<br />

<strong>VB</strong>.<strong>NET</strong><br />

Dim myCalculator As New Wrox.Samples.Calculator()<br />

C#<br />

Wrox.Samples.Calculator myCalculator = new Wrox.Samples.Calculator();<br />

Although you get some help from IntelliSense to f<strong>in</strong>d the Calculator class, typ<strong>in</strong>g these long names<br />

becomes bor<strong>in</strong>g after a while. Fortunately, there’s a fix for that as well.<br />

After you have created your own namespaces, or if you want to use exist<strong>in</strong>g ones, you need to make<br />

them available <strong>in</strong> your code. You do this with the keyword Imports (<strong>in</strong> <strong>VB</strong>.<strong>NET</strong>) or us<strong>in</strong>g (<strong>in</strong> C#).<br />

For example, to make your Calculator class available <strong>in</strong> the Calculator demo page without specify<strong>in</strong>g<br />

its full name, you can add the follow<strong>in</strong>g namespace to your code:<br />

<strong>VB</strong>.<strong>NET</strong><br />

Imports Wrox.Samples<br />

Partial Class Demos_CalculatorDemo<br />

Inherits System.Web.UI.Page<br />

C#<br />

us<strong>in</strong>g Wrox.Samples;<br />

public partial class Demos_CalculatorDemo : System.Web.UI.Page<br />

{<br />

With this Imports/us<strong>in</strong>g statement <strong>in</strong> place, you can now simply use Calculator aga<strong>in</strong> <strong>in</strong>stead of<br />

Wrox.Samples.Calculator.

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

Saved successfully!

Ooh no, something went wrong!