Importing static methods from a namespace in C# 6
February 23, 2016 Leave a comment
You’ll probably know that if you’d like to use the simple class names in a C# file you have to import its namespace in a using directive. If you want to use the Task class without referring to its fully qualified name including the namespace you have to put…
using System.Threading.Tasks;
…in the top section of the file. Then you can write something like…
Task t = Task.Run<ReturnType>(() => ...);
Similarly the using statement…
using System;
…is available by default in all new CS files in Visual Studio. The System namespace has a lot of members and one of them is the String class:
String startingPoint = "Hello world";
Checking whether a string is null or empty can be performed through a static method of the String class:
String.IsNullOrEmpty(startingPoint)
However, you cannot just refer to that static method by…
IsNullOrEmpty(startingPoint)
…even if you have imported the namespace where String is located. Let’s try the following:
using System.String;
We have no luck there of course, the compiler will complain:
A ‘using namespace’ directive can only be applied to namespaces; ‘string’ is a type not a namespace.
However, in C# 6 we can import the static members of a class as follows:
using static System.String;
Consider the following example where we use 3 static methods of String:
string startingPoint = "Hello world"; if (!String.IsNullOrEmpty(startingPoint)) { string toBePrinted = string.Format("I am saying {0}", string.Join(",", startingPoint, "some other string")); Console.WriteLine(toBePrinted); }
With the ‘using static’ statement in place we can simplify it to the following:
string startingPoint = "Hello world"; if (!IsNullOrEmpty(startingPoint)) { string toBePrinted = Format("I am saying {0}", Join(",", startingPoint, "some other string")); Console.WriteLine(toBePrinted); }
The compiler will now understand that you’re referring to the static methods of the String class.
Beware that if you have a method with the same signature available through a using statement or within the same class, e.g.:
private bool IsNullOrEmpty(string s) { return false; }
…then the compiler will refer to this method rather then String.IsNullOrEmpty.
Also, readers of the code may be wondering at first where the “Format” and “Join” methods are located. They certainly do not look like static methods just by looking at the code.
This feature is a neat addition to C# but be aware that it may cause some confusion.
View all various C# language feature related posts here.