15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

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

48 ❘ ChaPTer 2 cOre c#<br />

class Test<br />

{<br />

public static int Main()<br />

{<br />

Introduction::NamespaceExample NSEx =<br />

new Introduction::NamespaceExample();<br />

Console.WriteLine(NSEx.GetNamespace());<br />

return 0;<br />

}<br />

}<br />

namespace Wrox.ProCSharp.Basics<br />

{<br />

class NamespaceExample<br />

{<br />

public string GetNamespace()<br />

{<br />

return this.GetType().Namespace;<br />

}<br />

}<br />

}<br />

The main() meThod<br />

As you saw at the start of this chapter, <strong>C#</strong> programs start execution at a method named Main(). This must<br />

be a static method of a class (or struct), <strong>and</strong> must have a return type of either int or void.<br />

Although it is common to specify the public modifier explicitly, because by definition the method must be<br />

called from outside the program, it doesn’t actually matter what accessibility level you assign to the entrypoint<br />

method — it will run even if you mark the method as private.<br />

multiple main() methods<br />

When a <strong>C#</strong> console or Windows application is compiled, by default the compiler looks for exactly one<br />

Main() method in any class matching the signature that was just described <strong>and</strong> makes that class method<br />

the entry point for the program. If there is more than one Main() method, the compiler will return an error<br />

message. For example, consider the following code called DoubleMain.cs:<br />

using System;<br />

namespace Wrox<br />

{<br />

class Client<br />

{<br />

public static int Main()<br />

{<br />

MathExample.Main();<br />

return 0;<br />

}<br />

}<br />

class MathExample<br />

{<br />

static int Add(int x, int y)<br />

{<br />

return x + y;<br />

}<br />

public static int Main()<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!