Methods in C#
Methods in C#
• Method Access
Calling a method on an object is like accessing a field. After the object
name, add a period, the name of the method, and parentheses.
Arguments are listed within the parentheses, and are separated by
commas. The methods of the Motorcycle class can therefore be called
as in the following example:
Obj.method_name(“arguments”);
Methods
Method Parameters vs. Arguments
• Parameters act as variables inside the method which will store data that is
needed as input by an method.
E.g. double multiply(double n1, double n2); //here
(double n1, double n2)are parameters that will store the input value
given to the method.
• When calling code calls the method, it provides concrete values for each
parameter these values are called arguments. The value given as arguments
must be compatible with the parameter (data) type.
E.g. Form1.multiply(20.4,50.5); // here 20.4 and 50.5
are arguments, the values that are provided as input
to the multiply method.
Methods
• Methods can return a value to the calling code. The return keyword followed by a
value that matches the return type will return that value to the method.
• The return keyword also stops the execution of the method. If the return type is void,
a return statement without a value will stop the execution of the method otherwise
the method will stop when it reaches the last code line.
• Methods that are not declared void are required to use the return keyword to return a
value. if return statement is missing in such a method the compiler will generate error.
class SimpleMath
{
public double Square_Number(double number)
{
return number * number;
} }
Methods
• 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.
• It is necessary to initialize the value of the out parameter variable before returning
to the calling method.
• When out keyword is used the data only passed unidirectional (out of method).
ref
• The ref is a keyword in C# which is used for the passing the arguments by a reference.
• If any changes are made in this argument in the method will reflect in that variable
when the control return to the calling method.
• It is not necessary to initialize the value of a parameter before returning to the calling
method.
• Use out when a method needs to return multiple values and the
variables are uninitialized before calling the method.