Search code examples
c#inputboxmsgbox

In C# is there a way to shorten reference calls like Microsoft.VisualBasic.Interaction.MsgBox() to something like myMsgBox()?


I'm new to c# so I apologize if this is a stupidly obvious question, or if I worded it in a bad way.

I'm working on a VC# project that requires the use of the MsgBox() and InputBox() methods pretty frequently, and it's getting frustrating to either type the entire thing out or find it somewhere else in the code and copy-pasting it. First thing that came to mind is #define, but since it's a function and not a constant/variable, I'm not sure how to do that or if it's even possible.

Thanks in advance for your help.


Solution

  • You could create a delegate that invokes the desired method:

    Action<string> print = (s) => System.Console.WriteLine(s);
    

    Usage:

    print("hello");
    

    If you are fine with just shortening the namespace and class name you can use a type alias:

    using C  = System.Console;
    

    Usage:

    C.WriteLine("hello");
    

    With C# 6.0, you can even import all the static methods from a type:

    using static System.Console;
    

    Usage:

    WriteLine("hello");
    

    System.Console.WriteLine is just an here example, it works for any (static) method.