404 Not Found

404 Not Found


nginx

Method Basics

What Is a Method

A method is a block of code that performs a specific task. Encapsulating repeated logic into methods improves code reusability and readability.

In C#, methods must be defined inside a class or struct, unlike standalone functions in C. When using top-level statements, you can define local functions.

Method Definition and Invocation

Syntax

TEXT
access_modifier return_type method_name(parameter_list)
{
    method_body
}

Example

CSHARP
using System;

class Program
{
    static void SayHello()
    {
        Console.WriteLine("Hello, World!");
    }

    static void Main()
    {
        SayHello();
        SayHello();
    }
}
▶ Try it Yourself
TEXT
Hello, World!
Hello, World!
💡 To call a method, use the form method_name(arguments). A method only needs to be defined once and can be called multiple times.

Parameters and Return Values

Methods with Parameters

Parameters allow a method to receive data from outside, enabling it to process different inputs.

Example

CSHARP
using System;

class Program
{
    static void Greet(string name)
    {
        Console.WriteLine("Hello, " + name + "!");
    }

    static void Main()
    {
        Greet("Alice");
        Greet("Bob");
    }
}
▶ Try it Yourself
TEXT
Hello, Alice!
Hello, Bob!

Methods with Return Values

Return values allow a method to pass computation results back to the caller.

Example

CSHARP
using System;

class Program
{
    static int Add(int a, int b)
    {
        return a + b;
    }

    static void Main()
    {
        int result = Add(3, 5);
        Console.WriteLine("3 + 5 = " + result);
        Console.WriteLine("10 + 20 = " + Add(10, 20));
    }
}
▶ Try it Yourself
TEXT
3 + 5 = 8
10 + 20 = 30

Formal and Actual Parameters

Concept Description Example
Formal parameter Parameters in the method definition a, b in static int Add(int a, int b)
Actual parameter Values passed when calling the method 3, 5 in Add(3, 5)
⚠️ Formal parameters are variable declarations; actual parameters are specific values or expressions. When a method is called, the values of actual parameters are passed to the corresponding formal parameters.

The return Statement

The return statement serves two purposes:

  1. Return a result to the caller
  2. Immediately exit the method — subsequent code is not executed

Example

CSHARP
using System;

class Program
{
    static string GetGrade(int score)
    {
        if (score >= 90)
            return "Excellent";
        if (score >= 60)
            return "Pass";
        return "Fail";
    }

    static int Max(int a, int b)
    {
        if (a > b)
            return a;
        else
            return b;
    }

    static void Main()
    {
        Console.WriteLine(GetGrade(95));
        Console.WriteLine(GetGrade(70));
        Console.WriteLine(GetGrade(45));
        Console.WriteLine("Larger: " + Max(12, 8));
    }
}
▶ Try it Yourself
TEXT
Excellent
Pass
Fail
Larger: 12
⚠️ Once return is executed, the method ends immediately. In non-void methods, all code paths must return a value.

void Methods

void indicates that a method has no return value. void methods do not require a return statement, but you can use return; to exit early.

Example

CSHARP
using System;

class Program
{
    static void PrintLine(int length)
    {
        if (length <= 0)
            return;
        string line = new string('-', length);
        Console.WriteLine(line);
    }

    static void PrintInfo(string name, int age)
    {
        Console.WriteLine("Name: " + name);
        Console.WriteLine("Age: " + age);
    }

    static void Main()
    {
        PrintInfo("Alice", 18);
        PrintLine(20);
        PrintLine(-5);
    }
}
▶ Try it Yourself
TEXT
Name: Alice
Age: 18
--------------------
📌 return; in a void method is only used for early exit and does not return any value.

The Method Call Stack

The call stack is the memory management mechanism used when a program executes methods. Each time a method is called, a stack frame is pushed onto the stack; when the method returns, the frame is popped.

Example

CSHARP
using System;

class Program
{
    static int Square(int x)
    {
        return x * x;
    }

    static int SumOfSquares(int a, int b)
    {
        int sa = Square(a);
        int sb = Square(b);
        return sa + sb;
    }

    static void Main()
    {
        int result = SumOfSquares(3, 4);
        Console.WriteLine("Result: " + result);
    }
}
▶ Try it Yourself
TEXT
Result: 25

The call process is as follows:

TEXT
1. Main() pushed onto stack
2.   SumOfSquares(3, 4) pushed onto stack
3.     Square(3) pushed → returns 9 → popped
4.     Square(4) pushed → returns 16 → popped
5.   SumOfSquares returns 25 → popped
6. Main → outputs 25 → popped

ℹ️ The stack follows the "last in, first out" principle. The deeper the method nesting, the more stack frames there are. Stack space is limited; excessive recursion can cause a stack overflow.

Method Naming Conventions

C# method naming uses PascalCase: the first letter of each word is capitalized, with no underscores.

Style Example Language
PascalCase CalculateTotal, GetUserName C#
snake_case calculate_total, get_user_name C, Python

Example

CSHARP
using System;

class Program
{
    static double CalculateArea(double radius)
    {
        return 3.14159 * radius * radius;
    }

    static bool IsValidAge(int age)
    {
        return age >= 0 && age <= 150;
    }

    static void PrintUserInfo(string name, int age)
    {
        Console.WriteLine(name + ", age " + age);
    }

    static void Main()
    {
        double area = CalculateArea(5.0);
        Console.WriteLine("Area: " + area);
        Console.WriteLine("Valid age: " + IsValidAge(25));
        PrintUserInfo("Alice", 25);
    }
}
▶ Try it Yourself
TEXT
Area: 78.53975
Valid age: True
Alice, age 25

✅ Method names should start with a verb or verb phrase, such as Get, Set, Calculate, Is, Print, etc.

Expression-Bodied Methods

C# 6.0 introduced expression-bodied methods, using => to simplify single-line method definitions.

Example

CSHARP
using System;

class Program
{
    static int Square(int x) => x * x;

    static double CircleArea(double r) => 3.14159 * r * r;

    static bool IsAdult(int age) => age >= 18;

    static void Main()
    {
        Console.WriteLine(Square(7));
        Console.WriteLine(CircleArea(3.0));
        Console.WriteLine(IsAdult(20));
    }
}
▶ Try it Yourself
TEXT
49
28.27431
True
🚀 => is shorthand for a lambda expression, equivalent to { return expression; }, and only applies to single-line logic.

Pass by Value

C# uses pass by value by default: value types copy data, reference types copy the reference.

Example

CSHARP
using System;

class Program
{
    static void TryChange(int x)
    {
        x = 999;
    }

    static void Main()
    {
        int num = 10;
        TryChange(num);
        Console.WriteLine("num = " + num);
    }
}
▶ Try it Yourself
TEXT
num = 10
⚠️ With pass by value, the formal parameter is a copy of the actual parameter. Modifying the formal parameter inside the method does not affect the actual parameter.

Multiple Return Types

Methods can return various types: int, double, string, bool, etc.

Example

CSHARP
using System;

class Program
{
    static int GetLength(string text)
    {
        return text.Length;
    }

    static double GetAverage(int a, int b)
    {
        return (a + b) / 2.0;
    }

    static bool IsPositive(double value)
    {
        return value > 0;
    }

    static string BuildGreeting(string name)
    {
        return "Welcome, " + name + "!";
    }

    static void Main()
    {
        Console.WriteLine(GetLength("Hello"));
        Console.WriteLine(GetAverage(3, 4));
        Console.WriteLine(IsPositive(-2.5));
        Console.WriteLine(BuildGreeting("Alice"));
    }
}
▶ Try it Yourself
TEXT
5
3.5
False
Welcome, Alice!

❓ FAQ

Q Can a method have no parameters?
A Yes, just leave the parameter list empty, e.g. static void SayHi().

Q: Can a method have multiple return statements? A: Yes, but in non-void methods, every execution path must return a value.

Q: Can a void method use return? A: Yes, use return; to exit early, but it cannot return any value.

Q: Must formal and actual parameters have the same name? A: No, they are independent variables and can have different names.

Q: Can a C# method exist outside of a class? A: No, C# methods must be inside a class or struct, but local functions can be defined within top-level statements.

📖 Summary

  • A method consists of an access modifier, return type, method name, and parameter list
  • Formal parameters are variables in the definition; actual parameters are values passed at the call site
  • return returns a result and exits the method; void methods have no return value
  • The call stack manages method execution memory, following the last-in, first-out principle
  • C# method naming uses PascalCase conventions
  • Expression-bodied methods => simplify single-line method definitions
  • Default pass by value: value types copy data; modifying formal parameters does not affect actual parameters

📝 Exercises

  1. Write a static int Factorial(int n) method that calculates the factorial of n and returns the result
  2. Write a static bool IsEven(int num) method that checks whether an integer is even, using expression-bodied syntax
  3. Write a static void PrintMultiplicationTable(int n) method that prints the multiplication table for n (1×n through 9×n)
  4. Write a static string ClassifyScore(int score) method that returns "Excellent", "Good", "Pass", or "Fail" based on the score
  5. Write a static double CalcBMI(double weight, double height) method that calculates BMI from weight (kg) and height (m)
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏