static imports in c#

JavaC#.NetStatic Import

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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();

Solution 2 - Java

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.

Solution 3 - Java

C# 6.0 under Roslyn Platform supports Static import. It requires statement like:

using static System.Console;

so the code might look like:

using static System.Console;
namespace TestApplication
{
	class Program
	{
		static void Main(string[] args)
		{
			WriteLine("My test message");
		}
	}
}

The earlier planned version for C# 6.0 had static import without static keyword.

For other new features in C# 6.0 see: New Language Features in C# 6

Solution 4 - Java

Time marches on... it looks like C# might get static imports in the next version, see http://msdn.microsoft.com/en-us/magazine/dn683793.aspx for a preview.

using System;
using System.Console; // using the Console class here

public class Program
{
    public static void Main()
    {
        // Console.WriteLine is called here
        WriteLine("Hello world!");
    }
}

The official documentation for the 'Roslyn' C# compiler lists the feature as 'done'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIAdapterView Question on Stackoverflow
Solution 1 - JavaOdedView Answer on Stackoverflow
Solution 2 - JavaDarin DimitrovView Answer on Stackoverflow
Solution 3 - JavaHabibView Answer on Stackoverflow
Solution 4 - JavaMichiel van OosterhoutView Answer on Stackoverflow