Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have Global Methods in C#

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) ?

like image 841
Bruno Filip Avatar asked Dec 02 '25 13:12

Bruno Filip


1 Answers

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
    }
}
like image 104
Scott Chamberlain Avatar answered Dec 05 '25 02:12

Scott Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!