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,
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,
- 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,
- using static System.Console;
- namespace StaticNamespace
- {
- class Program
- {
- static void Main(string[] args)
- {
- Write("This is Test Value");
- ReadKey();
- }
- }
- }
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.
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.
We can use the same feature with our classes as well. Run the code and see the results. Happy coding!!