Is there a way to "Import" a static class in C# such as System.Math?
I have included a comparison.
Imports System.Math
Module Module1
Sub Main()
Dim x As Double = Cos(3.14) ''This works
End Sub
End Module
Vs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Math; //Cannot import a class like a namespace
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
double x = Math.Cos(3.14);
double y = Cos(3.14); //Cos does not exist in current context
}
}
}
UPDATE: As of C# 6, the answer is now YES.
No, in C# you can only import namespaces, not classes.
However, you can give it a shorter alias:
using M = System.Math;
Now you can use the alias instead of the class name:
double y = M.Cos(3.14);
Be careful how you use it, though. Most of the time the code is more readable with a descriptive name like Math
rather than a cryptic M
.
Another use for this is to import a single class from a namespace, for example to avoid conflicts between class names:
using StringBuilder = System.Text.StringBuilder;
Now only the StringBuilder
class from the System.Text
namespace is directly available.