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.
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.
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.
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With