Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static imports in c#

Does C# has feature like Java's static imports?

so instead of writing code like

FileHelper.ExtractSimpleFileName(file) 

I could write

ExtractSimpleFileName(file) 

and compiler would know that I mean method from FileHelper.

like image 997
IAdapter Avatar asked Oct 07 '11 21:10

IAdapter


People also ask

What do you mean by static import?

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 difference between import and static import?

Difference between import and static import: With the help of import, we are able to access classes and interfaces which are present in any package. But using static import, we can access all the static members (variables and methods) of a class directly without explicitly calling class name.

Should you use static imports?

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.


2 Answers

Starting with C# 6.0, this is possible:

using static FileHelper;  // in a member ExtractSimpleFileName(file) 

However, previous versions of C# do not have static imports.

You can get close with an alias for the type.

using FH = namespace.FileHelper;  // in a member FH.ExtractSimpleFileName(file) 

Alternatively, change the static method to an extension method on the type - you would then be able to call it as:

var value = file.ExtractSimpleFileName(); 
like image 200
Oded Avatar answered Sep 22 '22 07:09

Oded


No, such feature doesn't exist in C#. You need to specify the class that the static method belongs to unless you are already inside a method of this same class.

In C# though you have extension methods which kind of mimic this.

like image 25
Darin Dimitrov Avatar answered Sep 22 '22 07:09

Darin Dimitrov