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 Bob Smith was born on Earth
Methods can have parameters passed to them in order to change their behavior. Parameters are defined a bit like variable declarations but inside the parentheses of the method.
Inside the Person
class, add the following...