Content
As we all know Microsoft has launched a new version of C# called C# 6.0 with Visual Studio Ultimate 2015 Preview and there is new feature in C# 6.0 that is based on "Static Classes".
This feature allows us to access the static methods without using Class name each and every time. Let's see this feature.
I am using Visual Studio Ultimate 2015 Preview.
Open Visual Studio 2015 and select "File" -> "New" -> "Project..." and fill in the project name as "Console Application1".
After creating the project, I will access some common static methods in "program.cs" without the help of class name every time.
Basically we used to access the static methods using class name like:
Console: Generally we use to access the methods of the "Console" Class until C# 5.0.
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Hi");
- }
- }
Note: Here I am printing "Hi" using the "WriteLine()" method of the "Console" class.
But in C# 6.0, we can access the methods of the "Console" Class or static class directly. For this we need to access the "Console" class using "using" like namespaces.
- using System.Console;
-
- class Program
- {
- static void Main(string[] args)
- {
- WriteLine("Hi");
- }
- }
You can see there is a successful build with this code in Visual Studio Ultimate 2015 Preview.
Convert: Similarly we previously accessed the methods of the "Convert" Class until C# 5.0.
- class Program
- {
- static void Main(string[] args)
- {
- int i = Convert.ToInt32(8.0);
- }
- }
Note: Here I am converting the "double" value into an "Int" that is 8.0 using the "ToInt()" method of the "Convert" class.
But in C# 6.0, we can access the methods of the "Convert" class or static class directly. For this we need to access the "Convert" class using a "using" like namespaces.
- using System.Convert;
-
- class Program
- {
- static void Main(string[] args)
- {
- int i = ToInt32(8.0);
- }
- }
You can see there is successful build with this code in Visual Studio Ultimate 2015 Preview.
Math: Similarly we previously accessed the methods of the "Math" Class until C# 5.0.
- class Program
- {
- static void Main(string[] args)
- {
- Double i = Math.Sqrt(8.0);
- }
- }
Note: Here I am doing a Square Root of the "double" value that is 8.0 using the "Sqrt()" method of the "Math" Class.
But in C# 6.0, we can access the methods of the "Math" class or static class directly. For this we need to access the "Math" class using "using" like namespaces.
- using System.Math;
-
- class Program
- {
- static void Main(string[] args)
- {
- Double i = Sqrt(8.0);
- }
- }
You can see there is a successful build with this code in Visual Studio Ultimate 2015 Preview.
Conclusion: Now you understand the new feature of C# 6.0 that allows the use of the "Static Methods" in an easy way.