Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import a static method

Tags:

How can I import a static method from another c# source file and use it without "dots"?

like :

foo.cs

namespace foo {     public static class bar     {         public static void foobar()         {         }     } } 

Program.cs

using foo.bar.foobar; <= can't!  namespace Program {     class Program     {         static void Main(string[] args)         {              foobar();         }     } } 

I can't just foobar();, but if I write using foo; on the top and call foobar() as foo.bar.foobar() it works, despite being much verbose. Any workarounds to this?

like image 300
thkang Avatar asked Dec 28 '12 06:12

thkang


People also ask

How do I import a static method?

In Java, static import concept is introduced in 1.5 version. With the help of static import, we can access the static members of a class directly without class name or any object. For Example: we always use sqrt() method of Math class by using Math class i.e. Math.

What does import static means in Java?

Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static , to be used in Java code without specifying the class in which the field has been defined.

What is import and static import in Java?

The import allows the java programmer to access classes of a package without package qualification. The static import feature allows to access the static members of a class without the class qualification.

Should I use static import Java?

So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes.


1 Answers

With C# 6.0 you can.

C# 6.0 allows static import (See using Static Member)

You will be able to do:

using static foo.bar; 

and then in your Main method you can do:

static void Main(string[] args) {     foobar(); } 

You can do the same with System.Console like:

using System; using static System.Console; namespace SomeTestApp {     class Program     {         static void Main(string[] args)         {             Console.WriteLine("Test Message");             WriteLine("Test Message with Class name");         }    } } 

EDIT: Since the release of Visual Studio 2015 CTP, in January 2015, static import feature requires explicit mention of static keyword like:

using static System.Console; 
like image 174
Habib Avatar answered Sep 28 '22 13:09

Habib