Thread: namespace query
View Single Post
  #4 (permalink)  
Old August 9th, 2016, 02:45 PM
Rod Stephens's Avatar
Rod Stephens Rod Stephens is offline
Wrox Author
Points: 3,145, Level: 23
Points: 3,145, Level: 23 Points: 3,145, Level: 23 Points: 3,145, Level: 23
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jan 2006
Location: , , .
Posts: 641
Thanks: 2
Thanked 96 Times in 95 Posts
Default

Convert is a class defined in the System namespace. It has a bunch of static methods including ToInt32.

If you don't use any using statements, you could do this:

Code:
myDirection = System.Convert.ToInt32(System.Console.ReadLine());
This is the "most primitive" form.

If you include the System namespace, then you can use the classes it defines without explicitly giving the namespace like this:

Code:
using System;
...
myDirection = Convert.ToInt32(Console.ReadLine());
This using directive works for both Convert and Console because they are both inside that namespace.

This is what I would normally do because it's easy to tell that ToInt32 comes from the Convert class and ReadLine comes from the Console class.

You can also add the static keyword to gain transparent access to the static methods of classes like this:

Code:
using static System.Console;
using static System.Convert;
...
myDirection = ToInt32(ReadLine());
This is certainly shorter, but I think more confusing. And the three seconds you save in typing is often offset by three hours of debugging later.

You shouldn't be able to do this:

Code:
using System.Convert;
If you don't use the static keyword, then Visual Studio tries to treat System.Convert as a namespace, but it's a class not a namespace. If you add the static keyword, then it knows that you're using a class and not a namespace.

Last comment: When you use "using static System.Convert;" that doesn't automatically include anything else in the System namespace, just the static methods in the Convert class.

In fact, it doesn't even let you do this:

Code:
myDirection = Convert.ToInt32(ReadLine());
If you don't include the System namespace, then it can't find the Convert class, even though it can find that class's static members.
__________________
Rod

Rod Stephens, Microsoft MVP

Essential Algorithms: A Practical Approach to Computer Algorithms

(Please post reviews at Amazon or wherever you shop!)
Reply With Quote