MSDN Documentation

.NET Core Tutorials

Understanding Core Methods in .NET

Methods are the fundamental building blocks for creating executable code in .NET applications. They encapsulate a set of operations that perform a specific task. By organizing code into methods, you can promote reusability, improve readability, and simplify maintenance.

Defining Methods

A method definition includes the access level, return type, name, and parameters. The body of the method contains the statements that are executed when the method is called.

public string GreetUser(string userName)
{
    return $"Hello, {userName}!";
}
  • public: Access modifier, indicating the method can be called from anywhere.
  • string: The return type, specifying the data type of the value the method will return.
  • GreetUser: The name of the method.
  • (string userName): The parameter list. This method accepts one parameter, userName, of type string.
  • { ... }: The method body, containing the executable statements.

Method Parameters

Methods can accept zero or more parameters, which are values passed into the method to influence its behavior. Parameters are defined within the parentheses in the method signature.

There are different ways to pass parameters:

  • By Value: A copy of the argument is passed. Changes made to the parameter inside the method do not affect the original argument. This is the default for most types.
  • By Reference: A reference to the original argument is passed using the ref or out keywords. Changes made to the parameter inside the method *do* affect the original argument.
void AddNumbers(int a, int b, ref int sum)
{
    sum = a + b;
}

// Calling the method:
int result = 0;
AddNumbers(5, 10, ref result);
// 'result' will now be 15

Method Overloading

Method overloading allows you to define multiple methods in the same class with the same name, but with different parameter lists (different number of parameters, different types of parameters, or both). The compiler determines which method to call based on the arguments provided.

Example

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public double Add(double a, double b)
    {
        return a + b;
    }

    public int Add(int a, int b, int c)
    {
        return a + b + c;
    }
}

// Usage:
var calc = new Calculator();
int sum1 = calc.Add(5, 10);           // Calls the first Add method
double sum2 = calc.Add(5.5, 10.2);     // Calls the second Add method
int sum3 = calc.Add(5, 10, 15);        // Calls the third Add method

Return Values

Methods can return a value to the calling code using the return statement. The return type specified in the method signature must match the type of the value being returned. If a method does not return a value, its return type is void.

public int Multiply(int x, int y)
{
    int product = x * y;
    return product; // Returns an integer value
}

public void PrintMessage(string message)
{
    Console.WriteLine(message); // No return statement needed, return type is void
}

Access Modifiers

Access modifiers control the visibility and accessibility of methods. Common modifiers include:

  • public: Accessible from any other code.
  • private: Accessible only within the same class.
  • protected: Accessible within the same class or by classes derived from it.
  • internal: Accessible within the same assembly (project).
  • protected internal: Accessible within the same assembly or by derived classes in other assemblies.
  • private protected: Accessible within the same assembly and only by classes derived from the current class within that assembly.

Static Methods

Methods marked with the static keyword belong to the class itself, not to any specific instance of the class. They are called using the class name.

public class MathHelper
{
    public static int Square(int number)
    {
        return number * number;
    }
}

// Usage:
int squaredValue = MathHelper.Square(7); // Calls the static method

Instance Methods

Instance methods operate on the data (fields) of a specific object (instance) of a class. They are called on an object created from the class.

public class Person
{
    public string Name { get; set; }

    public void DisplayName()
    {
        Console.WriteLine($"The person's name is: {Name}");
    }
}

// Usage:
var person1 = new Person();
person1.Name = "Alice";
person1.DisplayName(); // Calls the instance method on the person1 object

Best Practices for Methods

  • Single Responsibility: Each method should perform a single, well-defined task.
  • Descriptive Names: Use clear and descriptive names that indicate the method's purpose.
  • Parameter Count: Aim for a small number of parameters. If a method requires many parameters, consider creating a parameter object.
  • Readability: Keep method bodies concise and easy to understand.
  • Avoid Side Effects: Methods should ideally perform their task without causing unexpected changes to the program's state, unless that is their intended purpose (e.g., methods that modify an object's state).
  • Consistency: Maintain a consistent style for naming and structuring your methods throughout your codebase.