Methods in C#

C# supports methods defined on struct types, similar to other object-oriented languages.

using System;

public struct Rect
{
    public int Width { get; set; }
    public int Height { get; set; }

    // This Area method is defined on the Rect struct.
    public int Area()
    {
        return Width * Height;
    }

    // Methods can be defined directly on the struct.
    public int Perim()
    {
        return 2 * Width + 2 * Height;
    }
}

class Program
{
    static void Main()
    {
        Rect r = new Rect { Width = 10, Height = 5 };

        // Here we call the 2 methods defined for our struct.
        Console.WriteLine($"area: {r.Area()}");
        Console.WriteLine($"perim: {r.Perim()}");

        // C# automatically handles method calls on struct instances.
        // There's no need for explicit pointer handling like in some other languages.
        Console.WriteLine($"area: {r.Area()}");
        Console.WriteLine($"perim: {r.Perim()}");
    }
}

To run the program, save it as Methods.cs and use the C# compiler:

$ csc Methods.cs
$ ./Methods
area: 50
perim: 30
area: 50
perim: 30

In C#, structs are value types, and methods are always called on the struct instance. There’s no concept of pointer receivers as in some other languages. If you need reference semantics, you would typically use a class instead of a struct.

Next, we’ll look at C#’s mechanism for grouping and naming related sets of methods: interfaces.