Simply put, methods are blocks of code containing a group of statements. They are functions that define a set of actions a type can perform; they can return output values and take input parameters.
In C#, methods are synonymous (the same) with functions, but their use has one significant difference: methods can only be defined in a type.
// Define a Person Type.
public class Person
{
private string _name = "John Doe";
// Method defined in Person.
public void SetName(string name)
{
_name = name;
}
}
Declaring a method is when you define its signature, which consists of an access modifier, optional modifier, return type, the method name, and any parameters. This is also called the method definition.
{accessor}-{modifier}-{type}-{MethodName}({ parameter }) { method body }
{public}---{none}-----{void}-{SetName}---({string name}) { method body }
A method can have more than one signature but not two identical signatures.
// Signature 1.
public void SetName(string name)
{
_name = name;
}
// Signature 2: This results in an error!
public void SetName(string firstName)
{
_name = firstName;
}
<aside> <img src="/icons/report_red.svg" alt="/icons/report_red.svg" width="40px" /> Pro-Tip
<aside> <img src="/icons/light-bulb_lightgray.svg" alt="/icons/light-bulb_lightgray.svg" width="40px" /> Every executed statement (line of code) is done within a method.
</aside>
<aside> <img src="/icons/light-bulb_lightgray.svg" alt="/icons/light-bulb_lightgray.svg" width="40px" /> The return type is not part of the method signature. This will only apply when checking compatibility with a delegate.
</aside>
</aside>