Writing and calling methods
Methods are type members that execute a block of statements. A method that performs some actions but does not return a value is marked as returning void
. A method that performs some actions and returns a value is marked as returning the type of that return value.
Inside the Person
class, statically import the System.Console
type and then add the following code:
// methods public void WriteToConsole() { WriteLine($"{Name} was born on {DateOfBirth:dddd, d MMMM yyyy}"); } public string GetOrigin() { return $"{Name} was born on {HomePlanet}"; }
Inside the Main
method, add the following code:
p1.WriteToConsole(); WriteLine(p1.GetOrigin());
Run the application and view the output:
Bob Smith was born on Wednesday, 22 December 1965 ...
Get C# 6 and .NET Core 1.0: Modern Cross-Platform Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.