Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 338
blitzilla Avatar asked Jan 25 '26 14:01

blitzilla


1 Answers

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.

like image 171
adjan Avatar answered Jan 27 '26 04:01

adjan



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!