Now that we have learned about the C# types and how to cast or convert them as well as basic code flow and the variety of operators we can work with, we can start learning about the most basic building blocks of C# programs: methods, parameters, and arguments.

A young boy stacks blocks, and they start to topple over.
Look out below! Photo by Ryan Fields / Unsplash

The Sample Project

exceptionnotfound/CSharpInSimpleTerms
Contribute to exceptionnotfound/CSharpInSimpleTerms development by creating an account on GitHub.
Project for this post: 6Methods

Methods

A method in C# is a code block which takes inputs and optionally returns an output. A method may also be called a function.

Methods have five parts:

  • An access modifier (e.g. public, private, etc.)
  • A return type
  • A name.
  • An optional set of parameters.
  • A collection of code statements bounded by curly braces { }.

Here's a basic method:

public string GetHello(string name)
{
    return "Hello " + name + "!";
}

Here, the access modifier is public, the return type is string, the name is GetHello, and there is one parameter: string name.

Method Invocation

A method is "invoked" when it is called to run by another part of the code. For example, we can invoke the GetHello method we wrote like so:

string name = "Jen";
var result = GetHello(name); //Method invocation AKA method call
Console.WriteLine(result); //Output: "Hello Jen!"

Access Modifier

Methods can have one of six access modifiers: public, private, protected, internal, protected internal, and private protected. Each of these access modifiers restricts the method in a different way.

For simplicity, the sample code in this post will only have public and private methods.

Return Types and Void

Methods can return any C# type, whether that is a primitive, class, struct, enumeration, etc.

Methods can also use the special return type void, which tells the C# compiler that the method will not return anything.

public string GetHello()
{
    return "Hello!";
}

public void DoSomething() { /*...*/}

string hello = GetHello();
DoSomething();

If our method has a return type but does not include the return keyword, we will get a compilation error.

public string GetGoodbye()
{
    string goodbye = "Goodbye!";
}
Error: not all code paths return a value.

Similarly, if our method has the return type void but attempts to return a value, we will get a different compilation error.

public void DoSomething()
{
    return "Something!";
}
Error: Since "DoSomething()" returns void, a return keyword must not be followed by an object expression.

Naming

The names of C# methods use Pascal Casing by convention; the first letter of every word in the method name should be capitalized. Note that you are not required to use Pascal Casing, but any method which does not use it will be seen as not conforming to standards.

Coming up with a good name for a method is a tricky subject; there are entire blog posts out there just for naming things. One tip we can follow is this: try to make it clear in the name what the method does and needs, without using too many words. The idea behind good naming is to communicate as much of the method's intent (or reason to exist) as possible.

Parameters

Methods can optionally define a set of parameters they can accept. A single method can take any number of parameters, and each parameter needs a type and a name included in the method definition.

The concrete values given to the method invocation are called arguments.

public int Add(int param1, int param2) //param1 and param2 are parameters
{
    return param1 + param2;
}

int value1 = 5; //Used as arguments below
int value2 = 16;

int sum = Add(value1, value2); //Sum == 21

Out Keyword

Occasionally we want to pass values to a method by reference rather than by value. We can do this using the out keyword in the method definition. This keyword is often used to allow the method to "return" more than one value.

string intString = "5";
int result;
bool hasValue = int.TryParse(intString, out result); //Result is now 5
C# itself does this with TryParse() methods, which we saw in Part 3: Casting, Conversion and Parsing.

out parameters may only be modified by the method they are passed to.

Ref Keyword

We can also pass parameters by reference using the ref keyword:

public void Sum(ref int total, int second)
{
    total = total + second;
}

int total = 17;
int nextNumber = 2;

Sum(ref total, nextNumber); //total is now 19
Sum(ref total, 6); //total is now 25

Unlike out parameters, ref parameters must be initialized (given a value) before they can be passed to a method.

In Keyword

We might also want to pass a value by reference but not allow the method to modify that value; in effect, this makes the value read-only. For this, we can use the in keyword.

double pi = 3.14159;

public double GetCircumference(double radius, in double pi)
{
    //pi = 3.14285; //Uncomment this line to get an error.
    return 2 * pi * radius;
}

Params Keyword

It is possible to pass an arbitrary number of parameters to a method, provided they are all of the same type. The params keyword allows a method to take a group of parameters and automatically create an array of the given values:

public decimal GetTotalPriceForSeats(params decimal[] seatPrices) 
{
    return seatPrices.Sum(); //Discussed in Part 14 - LINQ Basics
}

var totalPrice = GetTotalPriceForSeats(90, 91, 92, 93, 94);
Question for the audience: why do I not need the M literal here?

If a method uses a params parameter, it must be the last parameter listed in the method definition.

Optional Parameters

Methods in C# might have some of their parameters be optional. When such a method is invoked, the invocation does not need to pass an argument for optional parameters; instead, a default argument can be used.

To do this, we specify the default argument for the parameter in the method definition:

public int Increment(int startValue, int increment = 1) //Increment has
                                                        //a default value
{
    return startValue + increment;
}

int byOne = Increment(10); //11, because the default increment 1 is used
int byFive = Increment(10, 5); //15

Please note that if a method has optional parameters, they must appear in the parameters list after all the required parameters.

Named Arguments

We can even pass arguments to a method out of order, if we know the parameter names.

public double GetPyramidVolume(int height, int baseArea)
{
    return 0.33333333333 * height * baseArea;
}

var volume = GetPyramidVolume(baseArea: 12, height: 4);

Glossary

  • Method - a set of code instructions with a name, access modifier, return type, parameters, and curly braces.
  • Access modifiers - A set of keywords that determine what other code can access the class, method, property, etc. with the modifier.
  • Return type - The C# type being returned from a method.
  • Void - A special return type that says the method will return nothing.
  • Parameters - Names and types of values being passed into a method.
  • Arguments - Concrete values passed for parameters.
  • Pascal Casing - A naming scheme in which the first letter of every word is capitalized (e.g. ThisIsALongMethodName).

New Keywords

  • return - Ends the method, and if followed by an expression, returns the value of that expression (e.g. return "5"; or return myValue;)
  • void - When used as a return type, specifies that a method is not expected to return anything.
  • out - Used to pass parameters by reference. out parameters may only be modified by the method they are being passed to, and they do not need to be given a value before being passed to a method.
  • ref - Used to pass parameters by reference. Must be given a value before being passed to a method.
  • params - Used as a shortcut to pass a set of values of the same type to a method as a collection.

Summary

A method in C# is a code block that is executed when said method is invoked (called by another part of the code). A method must specify the parameters they can take, the type they return, their access modifier, and the lines of code they will execute.

Arguments (concrete values) are passed into method calls for each parameter in order to invoke the method. Many types of arguments can be used, including reference arguments, optional arguments, and named arguments.

In the next part of this series, we use all the knowledge we've gathered so far to learn about another foundational building block of any C# program: classes. Check it out!

C# in Simple Terms - Classes and Members
Let’s learn about C# class basics, including members, access levels, properties, methods, constructors, and more!

And, yes, the code in the post header image is JavaScript, not C#. Put your pitchforks down, please. :)

Happy Coding!