Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
You've learned how to call methods written by others. Now let's learn how to write your own!
Here I have another C# program. The first three lines of the Main
method display a message that we're waiting, pause for 3 seconds, and print another message that we're done waiting. The next three lines count from 1 to 3.
These are two separate tasks in the same program, but it's hard to tell at a glance which lines belong to which task, or what task they're supposed to be doing.
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Waiting...");
Thread.Sleep(3000);
Console.WriteLine("Done");
Console.WriteLine(1);
Console.WriteLine(2);
Console.WriteLine(3);
}
}
-
static
keyword means you can call the method all by itself; it doesn't belong to an object.-
GetType()
is an example of a method you can only call on an object. - Have to place a dot operator after an object, then call the method:
42.GetType();
- On the other hand,
Console.WriteLine()
is an example of astatic
method; a method you can call all by itself: -
WriteLine
takes arguments in parentheses, but you don't have to refer to an object, add a dot operator, and then call the method.
-
-
void
means no return value; we'll talk about return values shortly
static void Wait()
{
}
static void CountToThree()
{
}
- Method body in curly braces: one or more lines of code that will be run when method is called
- Lines of method body are usually indented to make it clear they're a part of the method, although this isn't required
static void Wait()
{
Console.WriteLine("Waiting...");
Thread.Sleep(3000);
Console.WriteLine("Done");
}
- Calling methods
- Method name followed by parentheses
- End statement with semicolon, as always
using System;
using System.Threading;
class Program
{
static void Wait()
{
Console.WriteLine("Waiting...");
Thread.Sleep(3000);
Console.WriteLine("Done");
}
static void CountToThree()
{
Console.WriteLine(1);
Console.WriteLine(2);
Console.WriteLine(3);
}
static void Main(string[] args)
{
Wait();
CountToThree();
}
}
The rules regarding the names you can use with a C# method are similar to the rules for naming variables.
- Unlike variables, though, the first letter of the name should be capitalized.
- As with variables, you should use camel case if there are multiple words. So every word after the first should be capitalized as well.
- And of course, you can't use C# keywords, and there should be no spaces in the method name.
OK:
Average
CalculateTax
Not OK:
average
Calculatetax
You need to sign up for Treehouse in order to download course files.
Sign up