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?
Declare an Action Delegate variable in a suitable scope as follows and use it later:
or even easier
I shall also pay attention to Extension Methods (C# Programming Guide). If you're having methods with parameters, often it's quite cosy to have:
and utilize it:
This is actually a much better approach.
With C# 6.0 you can.
C# 6.0 allows static import (See using Static Member)
You will be able to do:
and then in your
Main
method you can do:You can do the same with
System.Console
like:EDIT: Since the release of Visual Studio 2015 CTP, in January 2015, static import feature requires explicit mention of
static
keyword like:You can't
static methods needs to be in a class by design..
Why do static methods need to be wrapped into a class?
To add to the answers already here it's important to note that C# is a very typed language. Therefore, unless the method exists in the class you're in, you would never be able to do something like what you're looking for.
However, if you add the using:
You can then access it with just the type and method like this: