Bobski Bobski - 4 months ago 24
C# Question

C# static Main(string[] args)

Hi I'm trying to learn some C# programming and I came across something that I'm having a difficult time understanding. I usually deal with VB6, VB.Net, and VBA for the most part so i have some understanding of programming. here's what I'm not sure about...

Let's say you have two snippets of code...

1)

static int Area(int h, int w)
{
return h*w;
}


2)

static void Main(string[] args)
{
int res = Area(w: 5, h: 8);
console.writeline(res);
}


So in the first snippet, I'm doing the return which does the multiplication of H * W but we do not write it as we do in the #2 with
Console.Writeline()
? What does the return actually do?

In #2 - the first line
static void Main(string[] args)
- especially the string[] args part - What does this mean?

Answer

So in the first snippet, I'm doing the return which does the multiplication of H * W but we do not write it as we do in the #2 with console.writeline? What does the return actually do?

return represents what the function will return when called. The two parameters, h*w, must be supplied when the function is called, or a compiler error will be thrown. It's like an algebraic expression; the function represents that without needing to show the logic, just input two numbers and the functionality is applied as the return variable from the function. Using your example:

int res = Area(w: 5, h: 8)

Here, the function is called Area(w: 5, h: 8), with the w variable set to 5 and the h set to 8. Back to our function then:

static int Area(int h, int w)
{
  return h*w;
}

replace the variables, and you get:

static int Area(int h, int w)
{
   return 8*5;
}

So, it shouldn't surprise you that res = Area(w: 5, h: 8) gives res as 40, when you log it in the console.

In #2 - the first line static void Main(string[] args) - especially the string []args part - what does this mean?

The string[] args represents an array of arguments sent to the Main function, which is especially useful once you compile your script into an .exe. From the command line, you could do:

compiled.exe "My" "Strings"

and the array would contain two values; args[0] == "My" and args[1] == "Strings". You can loop through the args[] array to utilise them. In this script, the args array is not used.

EDIT Comment correction.