2

So I have a static class lets say its called Worker, and lets say I have a method inside it called Wait(float f) and its all public so I can acess it anywhere like so:

Worker.Wait(1000);

Now what I am wondering is there any way I can define some kind of unique special methods so I could just do it short like this:

Wait(1000);

(Without having it in the class I would use it in) ?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Bruno Filip
  • 139
  • 8
  • U can try one hack, make a C++ dll define method and call extern method without class name throughout C# project . – Vivek Nuna Nov 09 '16 at 20:21

3 Answers3

10

With C# 6 this can be done. At the top of your file you need to add a using static Your.Type.Name.Here;.

namespace MyNamespace
{

    public static class Worker
    {
        public static void Wait(int msec)
        {
            ....
        }
    }
}

//In another file

using static MyNamespace.Worker;

public class Foo
{
    public void Bar()
    {
        Wait(500); //Is the same as calling "MyNamespace.Worker.Wait(500);" here
    }
}
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
3

No, you cannot have methods that are not part of a class in C#.

Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
  • @ScottChamberlain Well even in C# 6 they are part of the class, that's just syntax sugar (as you of course know). – Evk Nov 09 '16 at 20:26
  • @Evk Yes, I know, but the op's question was "*is there any way I can define some kind of unique special methods so I could just do it short like this: `Wait(1000);`*" and the answer to that is yes, you can call it that way in C# 6. – Scott Chamberlain Nov 09 '16 at 20:27
  • @ScottChamberlain well I was confused because this answer you comment states "you cannot have methods that are not part of a class", and then you respond "this can be done in C# 6" :) – Evk Nov 09 '16 at 20:29
  • I agree @ScottChamberlain's answer is the right one, my answer is an answer to a bit of a different question. – Rok Povsic Nov 09 '16 at 20:31
  • I guess I was responding to what I felt was more the spirit of the answer of: "you cannot have methods that ***look like they*** are not part of a class" instead of the literal text. – Scott Chamberlain Nov 09 '16 at 20:31
3

No, you can not, Methods belong to a class, if you do Wait(1) is because you are in a class where that method is defined (or is the parent class)

Edit...

As commented that was true up to C# 5, this can be done in C# 6 now it can be done importing statically some classes...

take a look at Scott Chamberlain"s answer here and link to MSDN

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97