views:

82

answers:

3

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
        }
    }
}
+5  A: 

There isn't. You need to explicitly invoke methods as features of classes in C#.

CesarGon
+5  A: 

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.

Guffa
Good Suggestion!
Shiftbit
+1  A: 

I was thinking maybe some form of extension methods? This could be tweaked of course.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            double x = Math.Cos(3.14);
            double y = 3.14;
            Console.WriteLine(y.Cos());
        }
    }

    public static class Extension
    {
        public static double Cos(this double d)
        {
            return Math.Cos(d);
        }
    }
}
Shiftbit