I'm currently writing a C# console application and would like to give the user the ability to chose what feature to be executed. For example, when I start MyApp.exe -help the help should show, or when I start MyApp.exe -shutdown the computer should shutdown. How do I pass/check that?
My current code doesn't seem to work:
static void Main(string[] args)
{
if (args.Equals("-help"))
{
Console.WriteLine("Some help here...");
}
}
static void Main(string[] args)
{
ProcesArguments(args);
}
static void ProcesArguments(string[] parameters)
{
foreach (var parameter in parameters)
{
switch (parameter.ToLower())
{
case "-help":
DisplayHelp();
break;
case "-reboot":
RebootComputer();
break;
}
}
}
static void DisplayHelp()
{
Console.WriteLine($"Syntax: {System.AppDomain.CurrentDomain.FriendlyName} <Parameter>");
// ...
}
static void RebootComputer()
{
// ...
}
Args is an array, so you have to reference the argument by its index. So args[0] corresponds to the first argument passed in. In addition, check the array length first to ensure an argument was even provided before you try to access it.
static void Main(string[] args)
{
if (args.Length > 0 && args[0] == "-help")
{
Console.WriteLine("Some help here...");
}
}
args is an array so you need to look for -help occurrence in it. You can achieve it using String.Contains() method.
static void Main(string[] args)
{
if (args.Contains("-help"))
{
Console.WriteLine("Some help here...");
}
}
Related
Let's assume that we have got simple program like below. Is it even possible to make some action on unexpected quit of the program?
static void Main(string[] args)
{
}
public void onKillDoSomething()
{
...
}
In C# , in Visual Studio, using a Console Application, is there a way to make methods in a class and call them in main program using readline?
Aka, a way to choose which methods to open when the program is running.
Easiest way is a switch statement for <4 cases, and a Dictionary for 4 or more cases.
class Program
{
private static IDictionary<string, Action> MethodMappings = new Dictionary<string, Action> {
{"Method1", Method1},
{"Method2", Method2},
...
}
public static void Main(string[] args) {
var methodCall = Console.ReadLine();
if (!MethodMappings.ContainsKey(methodCall)) {
//unrecognized command
}
MethodMappings[methodCall].Invoke();
}
private static void Method1() { ... }
private static void Method2() { ... }
}
This is very much possible using Reflection. Here is sample code to help you out:
class Program
{
public static void Hello1()
{
Console.WriteLine("\nHello 1");
}
public static void Hello2()
{
Console.WriteLine("\nHello 2");
}
static void Main(string[] args)
{
while (true)
{
String method = Console.ReadLine();
Type methodType = typeof(Program);
MethodInfo voidMethodInfo = methodType.GetMethod(method);
voidMethodInfo.Invoke(method,null);
}
}
}
For more information you can visit here.
How CLR knows which method to call since they are returning different value(One is void and another is int) ? In sense of Overloading this is also not right, a method with same parameter with different return type.
example:
class Program
{
static int Main(String[] args) //Main with int return type but Parameter String[] args
{
return 0;
}
/* this main method also gonna get called by CLR even though return type void and Same parameter String[] args.
static void Main(String[] args) //Main with int return type but String[] args
{
} */
private static void func(int one)
{
Console.WriteLine(one);
}
private static int func(int one) //compiler error. two overloaded method cant have same parameter and different return type.
{
return 1;
}
}
but main method is not maintaining overloading rules.
in .NET, an executable can have only one entry point i.e. only one Main method is allowed. To be more specific, the Main method is considered as an entry point only if the sigature matches any of the below 2 and the method is static.
Main(String[])
Main()
If, you provide a main method whose signature is different from above two, it is not considered as Main method. So, below code is allowed,
class Program
{
static void Main () //Entry point
{
}
static void Main(int number)
{
}
}
The below code doesn't compile because, it finds matching signature at two places.
class Program
{
static void Main () //Entry point
{
}
static void Main(String[] args) //another entrypoint!!! Compile Error
{
}
}
Below code also doesn't compile because there is no entry point at all,
class Program
{
static void Main (int a) //Not an Entry point
{
}
static void Main(float b) //Not an entry point
{
}
}
i am trying to create a macro with jitbit macro recorder, what i need is if statement for shortcuts, like "ctrl+y", but software doesnt have if statement for shourtcuts. But there is Run "C# code" feature. I am trying to create a code for this. but failed so far.Can anyone help me?
Note: code must contain a class named Program with the static method Main.
Here is example code from the macro recorder;
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
Maybe this is what you are searching for:
class Program
{
static void Main(string[] args)
{
ConsoleKeyInfo keyinfo;
do
{
keyinfo = Console.ReadKey(true);
if (keyinfo.Modifiers == ConsoleModifiers.Control)
{
if (keyinfo.Key == ConsoleKey.Y)
{
// Do something
}
else if (keyinfo.Key == ConsoleKey.Z)
{
// Do something else
}
}
}
while (keyinfo.Key != ConsoleKey.X); // Ends the program if you press X
}
}
I want to pass a method ( of void return type and with no input arguments) as parameter using C#. Below is my sample code. How can I do it ?
public void Method1()
{
... do something
}
public int Method2()
{
... do something
}
public void RunTheMethod([Method Name passed in here] myMethodName)
{
myMethodName();
... do more stuff
}
System.Action will fit the bill:
http://msdn.microsoft.com/en-us/library/system.action.aspx
You've also got various generic versions of Action for methods that have parameters but have a void return type, and Func for methods that return something.
So your RunTheMethod method would look like
public void RunTheMethod(Action myMethod)
{
myMethod();
}
Then you can call it with:
RunTheMethod(Method1);
RunTheMethod(Method2);
As mentioned before, you can use delegates – in your case, you could use System.Action to do exactly that.
public void RunTheMethod(System.Action myMethodName)
{
myMethodName();
... do more stuff
}
Take a look at delegates which act like a pointer to a method
You should look at Delegates to get a solution to your query. They basically serve as a pointer or reference to a function.
Also take a look at this example for a better understanding.
//Delegate
public delegate void OnDoStuff();
class Program
{
static void Main(string[] args)
{
//Pass any of the method name here
Invoker(Method1);
Console.ReadLine();
}
private static void Invoker(OnDoStuff method)
{
method.Invoke();
}
private static void Method1()
{
Console.WriteLine("Method1 from method " + i);
}
private static void Method2()
{
Console.WriteLine("Method2 from method " + i);
}
private static void Method3()
{
Console.WriteLine("Method3 from method " + i);
}
}