2

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.

blitzilla
  • 31
  • 2
  • use a `using Microsoft.VisualBasic.Interaction` on top of your your source-code-file. Have a look at the [`using`-directive](https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/using-directive). – MakePeaceGreatAgain May 06 '18 at 16:49
  • 2
    What type of app you develop? WinForms? WPF? For WPF - [MessageBox](https://learn.microsoft.com/en-us/dotnet/api/system.windows.messagebox). For WinForms - [MessageBox](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.messagebox). – JohnyL May 06 '18 at 16:53

2 Answers2

6

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.

adjan
  • 13,371
  • 2
  • 31
  • 48
2

You can use using static if you are using C# 6:

using static Microsoft.VisualBasic.Interaction;

This allows to call any method of a static class (here Interaction) without referencing it later in code again. So with this you can call MsgBox() instead of Interaction.MsgBox()

arekzyla
  • 2,878
  • 11
  • 19