Functions

C# Methods

Defining C# Methods

C# methods use typed parameters and return types.

Introduction to C# Methods

Methods in C# are blocks of code designed to perform a specific task. A method can take inputs, perform operations, and return a result. This helps in organizing code, reusing functionality, and enhancing readability.

Every method in C# must belong to a class or struct, and it can be called from other parts of the program. Methods can have parameters and return types, making them powerful tools in any developer's toolkit.

Defining a Method

Defining a method in C# involves specifying the access level, return type, method name, and any parameters. Here's a typical structure:

  • Access Modifier: Defines the visibility of the method (e.g., public, private).
  • Return Type: Specifies what kind of value the method will return. Use void if no value is returned.
  • Method Name: Should be descriptive of the task it performs.
  • Parameters: Inputs required by the method, enclosed in parentheses.

Calling a Method

Once a method is defined, it can be called from other parts of the program. To call a method, you use its name followed by parentheses. If the method requires parameters, provide them within the parentheses.

Here's how you might call the Add method from the Calculator class:

Method Parameters and Return Types

Parameters allow methods to accept inputs. In C#, parameters are strongly typed, meaning you must specify the type of each parameter. For example, int a and int b in the Add method specify that both parameters must be integers.

The return type specifies what type of data the method will produce. If a method performs an action without returning a value, its return type is void.

Method Overloading

Method overloading allows you to define multiple methods with the same name but different parameters. This is useful when you want a method to handle different types or numbers of inputs.

Here's an example of method overloading:

In the example above, the Print method is overloaded to handle both integers and strings. The correct method is chosen based on the argument type passed during the call.

Previous
Console