Writing and Calling Methods
Learn about methods in C#, including returning values, using tuples, and deconstructing types to extract information efficiently.
Methods are members of a type that execute a block of statements. They are functions that belong to a type.
Returning values from methods
Methods can return a single value or return nothing:
A method that performs some actions but does not return a value indicates this with the
void
type before the method’s name.A method that performs some actions and returns a value indicates this with the return value type before the method’s name.
For example, in the next task, we will create two methods:
WriteToConsole
: This will act (writing some text to the console) but will return nothing from the method indicated by thevoid
keyword.GetOrigin
: This will return a text value indicated by thestring
keyword.
Let’s write the code:
Step 1: In Person.cs
, add statements to define the two methods that were described earlier, as shown in the following code:
// methodspublic void WriteToConsole(){WriteLine($"{Name} was born on a {DateOfBirth:dddd}.");}public string GetOrigin(){return $"{Name} was born on {HomePlanet}.";}
Step 2: In Program.cs
, add statements to call the two methods, as shown in the following code:
bob.WriteToConsole();WriteLine(bob.GetOrigin());
Step 3: Run ...