The out parameter in C# is a keyword used to pass arguments by reference, allowing a method to return multiple values or modify variables outside its scope.
Unlike regular parameters, variables passed as out arguments do
not need to be initialized before the method call.
Key
Characteristics
- Passing by Reference: When an argument is passed
with out, the method works with the same memory location as the
original variable, so any changes made inside the method are reflected in
the calling code.
- Mandatory Assignment: The called method must
assign a value to all out parameters before it returns;
the code will not compile otherwise.
- No Initial Value Required: The calling code is not
required to initialize the variable before passing it to an out parameter.
This is the primary difference from the ref keyword, which
requires initialization.
- Multiple Return Values: It is commonly used when a
method needs to return more than one piece of data, in scenarios like
the int.TryParse pattern, where a boolean return value indicates
success and the out parameter provides the result.
using System;
using static
System.Console;
namespace OutExample
{
class Program
{
static void Main(string[] args)
{
WriteLine("Please enter
radious for circle");
double radious = Convert.ToDouble(ReadLine());
double circumference = CalculateCircle(radious,
out double area);
WriteLine("Circle's
circumference is "+circumference);
WriteLine("Circle's Area is "+area);
}
static double CalculateCircle(double
radious, out double area)
{
area = 3.14 *radious*radious;
double circumference = 2 * Math.PI *
radious;
return circumference;
}
}}
No comments:
Post a Comment