In the "Hello, World" application, we used the Console.WriteLine method that's defined in the System namespace. In fact, all .NET types and classes are defined in namespaces. However, we didn't create a namespace for our application, so let's address that issue.
Namespaces are a great way of categorizing your types and classes so as to avoid name collisions. Microsoft places all the .NET class and type definitions in specific namespaces because it wants to make sure that its names don't conflict with the names of anyone using its compilers. However, whether you should use namespaces comes down to one question: will the types and classes you create be used in an environment not controlled by you? In other words, if your code is being used only by members of your own team, you can easily create naming rules such that name collision doesn't occur. However, if you're writing classes that will be used by third-party developers, in which case you don't have any control over naming practices, you should definitely use namespaces. In addition, since Microsoft recommends using your company name as the top-level namespace, I would recommend using namespaces anytime someone else might see your code. Call it free advertising.
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Saturday, January 30, 2010
Skeleton Code
Let's quickly look at what can be viewed as skeleton code for most any C# application, code that illustrates a basic outline for a simple, no-frills C# application. You might want type this into a file and save it to use as a template in the future. Notice that the angle brackets denote where you need to supply information.
usingnamespace class { public static void Main() { } }
Class Ambiguity In the case of a type being defined in more than one referenced namespace, the compiler will emit an error denoting the ambiguity. Therefore, the following code will not compile because the class C is defined in two namespaces that are both referenced with the using directive: -
using A;
using B;
namespace A
{
class C
{
public static void foo()
{
System.Console.WriteLine("A.C.foo");
}
}
}
namespace B
{
class C
{
public static void foo()
{
System.Console.WriteLine("B.C.foo");
}
}
}
class MultiplyDefinedClassesApp
{
public static void Main()
{
C.foo();
}
}To avoid this type of error, make sure to give your classes and methods unique, descriptive names.
Labels:
C#
Subscribe to:
Posts (Atom)