Writing and Calling Methods
Explore how to write and call methods in C#, including those that return values or void. Understand tuples as a way to return multiple values efficiently, how to name their fields, and use tuple deconstruction for cleaner code. Learn to implement deconstruct methods in custom types to unpack objects into parts automatically.
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
voidtype 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 thevoidkeyword.GetOrigin: This will return a text value indicated by thestringkeyword.
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:
Step 2: In Program.cs, add statements to call the two methods, as shown in the following code:
Step 3: ...