Skip to main content This browser is no longer supported. Show
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. Methods in C#
In this articleA method is a code block that contains a series of statements. A program causes the
statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method. The Note This topic discusses named methods. For information about anonymous functions, see Lambda expressions. Method signaturesMethods are declared in a
These parts together form the method signature. Important A return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to. The following example defines a class named
The Method invocationMethods can be either instance or static. Invoking an instance method requires that you instantiate an object and call the method on that object; an instance method operates on that instance and its data. You invoke a static method by referencing the name of the type to which the method belongs; static methods don't operate on instance data. Attempting to call a static method through an object instance generates a compiler error. Calling a method is like accessing a field. After the object name (if you're calling an instance method) or the type name (if you're calling a The method definition specifies the names and types of any parameters that are required. When a caller invokes the method, it provides concrete values, called arguments, for each parameter. The arguments must be compatible with the parameter type, but the argument name, if one is used in the calling code, doesn't have to be the same as the parameter named defined in the method. In the
following example, the
The most common form of method invocation used positional arguments; it supplies arguments in the same order as method parameters. The methods of the
You can also use named arguments instead of positional arguments when invoking a method. When using named arguments, you specify the parameter name followed by a colon (":") and the argument. Arguments to the method can appear in any order, as long as
all required arguments are present. The following example uses named arguments to invoke the
You can invoke a method using both positional arguments and named arguments. However, positional arguments can only follow named arguments when the named arguments are in the correct positions. The following example invokes the
Inherited and overridden methodsIn addition to the members that are explicitly defined in a type, a type inherits members defined in its base classes. Since all types in the managed type system inherit directly or indirectly from the Object class, all types inherit
its members, such as Equals(Object), GetType(), and
ToString(). The following example defines a
Types can override inherited members by using the
Passing parametersTypes in C# are either value types or reference types. For a list of built-in value types, see Types. By default, both value types and reference types are passed to a method by value. Passing parameters by valueWhen a value type is passed to a method by value, a copy of the object instead of the object itself is passed to the method. Therefore, changes to the object in the called method have no effect on the original object when control returns to the caller. The following example passes a value type to a method by value, and the called method attempts to change the value type's value. It defines a variable of type
When an object of a reference type is passed to a method by value, a reference to the object is passed by value. That is, the method receives not the object itself, but an argument that indicates the location of the object. If you change a member of the object by using this reference, the change is reflected in the object when control returns to the calling method. However, replacing the object passed to the method has no effect on the original object when control returns to the caller. The following example defines a class (which is a reference type) named
Passing parameters by referenceYou pass a parameter by reference when you want to change the value of an argument in a method and want to reflect that change when control returns to the calling method. To pass a parameter by reference, you use the
The following example is identical to the previous one, except the value is passed by reference to the
A common pattern that uses by ref parameters involves swapping the values of variables. You pass two variables to a method by reference, and the method swaps their contents. The following example swaps integer values.
Passing a reference-type parameter allows you to change the value of the reference itself, rather than the value of its individual elements or fields. Parameter arraysSometimes, the requirement that you specify the exact number of arguments to your method is restrictive. By
using the A caller can then invoke the method in either of four ways:
The following example defines a method named
Optional parameters and argumentsA method definition can specify that its parameters are required or that they're optional. By default, parameters are required. Optional parameters are specified by including the parameter's default value in the method definition. When the method is called, if no argument is supplied for an optional parameter, the default value is used instead. The parameter's default value must be assigned by one of the following kinds of expressions:
If a method includes both required and optional parameters, optional parameters are defined at the end of the parameter list, after all required parameters. The following example defines a method,
If a method with multiple optional arguments is invoked using positional arguments, the caller must supply an argument for all optional parameters from the first one to the last one for which an argument is supplied. In the case of the If a method is called using named arguments or a combination of positional and named arguments, the caller can omit any arguments that follow the last positional argument in the method call. The following example calls the
The use of optional parameters affects overload resolution, or the way in which the C# compiler determines which particular overload should be invoked by a method call, as follows:
Return valuesMethods can return a value to the caller. If the return type (the type listed before the method name) isn't If the return type is For example, these two methods use the
To use a value returned from a method, the calling method can use the method call itself anywhere a value of the same type would be sufficient. You can also assign the return value to a variable. For example, the following two code examples accomplish the same goal:
Using a local variable, in this case, Sometimes, you want your method to return more than a single value. You can do this easily by using tuple types and tuple literals. The tuple type defines the data types of the tuple's elements. Tuple literals provide the actual values of the returned tuple. In the following example,
The caller can then consume the returned tuple with code like the following:
Names can also be assigned to the tuple elements in the tuple type definition. The following example shows an alternate version of the
The previous call to the
If a method is passed an array as an argument and modifies the value of individual elements, it isn't necessary for the method to return the array, although you may choose to do so for good style or functional flow of values. This is because C# passes all reference types by value, and the value of an array reference is the pointer to the array. In the following example, changes to the contents of the
Extension methodsOrdinarily, there are two ways to add a method to an existing type:
Extension methods let you "add" a method to an existing type without modifying the type itself or implementing the new method in an inherited type. The extension method also doesn't have to reside in the same assembly as the type it extends. You call an extension method as if it were a defined member of a type. For more information, see Extension Methods. Async MethodsBy using the async feature, you can invoke asynchronous methods without using explicit callbacks or manually splitting your code across multiple methods or lambda expressions. If you mark a method with the
async modifier, you can use the await operator in the method. When control reaches an Note An async method returns to the caller when either it encounters the first awaited object that's not yet complete or it gets to the end of the async method, whichever occurs first. An async method typically has a return type of
Task<TResult>, Task, IAsyncEnumerable<T>or In the following example,
An async method can't declare any in, ref, or out parameters, but it can call methods that have such parameters. For more information about async methods, see Asynchronous programming with async and await and Async return types. Expression-bodied membersIt's common to have method definitions that simply return immediately with the result of an expression, or that have a single statement as the body of the method. There's a syntax shortcut for defining such methods using
If the method returns IteratorsAn iterator performs a custom iteration over a collection, such as a list or an array. An iterator uses the yield return statement to return each element one at a time. When a The return type of an iterator can be IEnumerable, IEnumerable<T>, IAsyncEnumerable<T>, IEnumerator, or IEnumerator<T>. For more information, see Iterators. See also
FeedbackSubmit and view feedback for When a method is mean that multiple methods in the same class have the same name but use different types of parameters?The practice of defining two or more methods within the same class that share the same name but have different parameters is called overloading methods.
What is it called when the same method name is used by multiple methods with different parameters?If a class has multiple methods having same name but parameters of the method should be different is known as Method Overloading.
What is it called when two methods have the same name but different parameter lists?Method overloading means two or more methods have the same name but have different parameter lists: either a different number of parameters or different types of parameters.
Are methods which are in the same class and have the same name but different parameter lists?Overloading occurs when two or more methods in one class have the same method name but different parameters.
|