Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed C# Basics!
You have completed C# Basics!
It's important to know that having a method print output using Console.WriteLine is not the same as having a method return a value.
It's important to know that having a method print output using Console.WriteLine is not the same as having a method return a value. If you confuse the two, your programs are going to behave strangely, and you won't know why. So I wanted to spend this video clarifying the difference.
- Here's a version of our program with the
Subtractmethod removed. - Suppose I remove the
returnstatement from theAddmethod, and instead passed the result of adding the numbers toConsole.Writeline:Console.WriteLine(first + second); - I'll get an error: "'Program.Add(double, double)': not all code paths return a value"
static double Add(double first, double second)
{
Console.WriteLine(first + second);
}
- Converting the return type of
Addtovoidgets theAddmethod declaration to compile...- But then we get the error "Cannot implicitly convert type 'void' to 'double'" when the code down in
Mainexpects a return value.
- But then we get the error "Cannot implicitly convert type 'void' to 'double'" when the code down in
static void Add(double first, double second)
{
Console.WriteLine(first + second);
}
static void Main(string[] args)
{
double total = Add(3, 5);
Console.WriteLine(total);
}
- Just remember, if you want your method to give information to a human, you can call
Console.WriteLine. - But if you want your method to give information back to your program, you need to specify a return type and use the
returnkeyword instead.
static double Add(double first, double second)
{
return first + second;
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up