Static Namespace In C# 6.0

Since the new .NET Framework has been announced, several new features have been introduced in C# with its new version. Here, let us learn the concept of using the static classes as a namespace using the using keyword.

Typically, when we have static classes with methods, we call the method using the convention staticClassName.MethodName. But with the new features in C# 6.0, we can directly call the static methods, like they are part of the same classes, instead of using the convention of staticClassName.MethodName. Let's see how to do this.

For our example, let's create a new console application and use the old convention of calling the WriteLine method. So we write the code as,

Static As Namespace In C# 6.0

Now in C# 6.0, we can directly call the Console method. To do this, we first need to add the static class with the following code. In our case, the class is Console. We add it as,
  1. using static System.Console;  
Note the use of the static keyword to refer to the Console class. Now we can directly refer to the Write or WriteLine methods of the Console class. See the code below,
  1. using static System.Console;    
  2. namespace StaticNamespace  
  3. {  
  4.   class Program  
  5.   {   
  6.     static void Main(string[] args)  
  7.     {  
  8.        Write("This is Test Value");  
  9.        ReadKey();  
  10.     }  
  11.   }  
  12. }  
See, ReadKey is also a static method and we are able to access that method directly here. So run the application and see the results.
 
 Static As Namespace In C# 6.0

Now, let's try the same thing using our custom classes. So we add a new static class called MyStaticClass and add a new method that returns a string value as in the following.

 Static As Namespace In C# 6.0

We can use the same feature with our classes as well. Run the code and see the results. Happy coding!!


Recommended Free Ebook
Similar Articles