Learn about ref and out keywords in Asp.Net

5
(1)

Learn about ref and out keywords in Asp.Net

 

ref keyword

ref keyword used to pass arguments by reference and not value, i.e. any changes made to this argument inside the called method will be reflected in that variable when control returns to the calling method.
To use the ‘ref’ keyword, you need to explicitly mention ‘ref’ keyword with the argument in called function. The ref parameter does not pass the property.

Public void _ReerenceMethod(ref int marks) {
marks= marks+ 10;
}
int _marks = 55;
_ReerenceMethod(ref _marks );
Console.WriteLine(_marks );
// Output: 65

 

out keyword

The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. The out parameter does not pass the property. it is very much similar to the ref keyword, however, the ref keyword needs to be initialized before it is passed.

static public void Main() {
// Declaring variable, without assigning value
int _marks;
// Pass variable G to the method using out keyword
Sum(out _marks);
Console.WriteLine("Total value is: {0}", _marks);
}

public static void Sum(out int marks){
marks= 40;
marks += marks;
}

The sum of the value is: 80

 

Both out and ref keywords are useful when we want to return a value in the same variables that are passed as an argument.

 

ref keyword out keyword
parameters should initialize first, before it pass to ref. It is not necessary to initialize parameters before it pass to out.
It is not necessary to initialize the value of a parameter before returning to the calling method. It is necessary to initialize the value of a parameter before returning to the calling method.
The passing of value through ref parameter is useful when the called method also need to change the value of passed parameter. The declaring of parameter through out parameter is useful when a method return multiple values.
When ref keyword is used the data may pass in bi-directional. When out keyword is used the data only passed in unidirectional.

 

Both ref and out are treated differently at run time, while treated same at compile time

 

More on Asp.Net …

 

 

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

1 Trackback / Pingback

  1. C# (Asp.Net) Interview Questions - etechstuffs

Leave a Reply

Your email address will not be published.


*


9 + ten =