C# Method/function Concepts and Advanced Features
- Why
Suppose we want to calculate sum of two number say a, b we can implement by direct implementation like a + b.
1 2 3
var a = 7; var b = 50; var c = a+b;
Now Take The Cases
- number should be positive
- Maxium value of number cant be greater than 100
- Sum of Both number should be less than 100 and greater than 30
- ans aso on.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
var a = 7; var b = 50; if (a>0 && b>0) { if(Math.Max(a,b)<100) { var c = a+b; if(c<100 && c>=30) { Console.WriteLine($"Sum Of Number is {c}"); } else { Console.WriteLine("Sum of Both number should be less than 100 and greater than 30"); } } else { Console.WriteLine("Number Should Be less Than 100"); } } else { Console.WriteLine("Number Should Be Positive"); }
Imagine this validation is require in more than one place then our code will be Explode Exponentially
It Will be Hard TO Main tain Also
To Solve this Issue We Use Function. Like this for Above example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
public string Sum(int a, int b) { if (a>0 && b>0) { if(Math.Max(a,b)<100) { var c = a+b; if(c<100 && c>=30) { return $"Sum Of Number is {c}"; } else { return "Sum of Both number should be less than 100 and greater than 30"; } } else { return "Number Should Be less Than 100"; } } else { return "Number Should Be Positive"; } }
More Detailed Explanation Below With Different Cases And Example
Return Type
A method can return a value. The return type of the method must be specified. it dosen’t return any value than void is used
Example: Return Type
|
|
|
|
Parameters
Methods can take parameters to perform operations with input values.
Example: Parameters
|
|
Default Parameters
Methods can have default parameters, which are used if no arguments are provided when the method is called.
Example: Default Parameters
|
|
Method Overloading
Method overloading allows multiple methods with the same name but different parameters.
Example: Method Overloading
|
|
Optional Parameters
Optional parameters have default values and can be omitted when the method is called.
Example: Optional Parameters
|
|
More Adavanced
Ref and Out Parameters
The ref
and out
keywords allow passing parameters by reference or returning multiple values.
Example: Ref and Out Parameters
|
|
Lambda Expressions
Lambda expressions provide a concise way to define anonymous methods using the =>
syntax.
Example: Lambda Expressions
|
|
Delegate Methods
Delegates are types that represent references to methods. They are used to pass methods as arguments to other methods.
Example: Delegate Methods
|
|
Async Methods
Asynchronous methods allow operations to run asynchronously, improving performance for I/O-bound operations.
Example: Async Methods
|
|
Extension Methods
Extension methods allow you to add new methods to existing types without modifying the original type.
Example: Extension Methods
|
|