Pages

Wednesday, May 22, 2013

difference between the ref and out keywords in C#

Ref Keyword:

1.By using ref keyword we can pass argument by reference.
2.The ref effect is that any changes made to that variable is possible to declare method when control passback to the calling method.
3.Any argument passed to a ref parameter must be initialize before passing the method. 

sample code:

{
  int x=10;
  m(ref x);
Response.write(x);
 }
public void m(ref int x)
   {

   }
}
output: no error(some value will be come)

Out keyword:

1.The out keyword causes argument ,this is just like ref keyword ,except required that value to be initialize before its passed.
2.variable pass as out argument ,do not have initialize before being passed ,the calling method is requred to assign a value before the method.

sample code:


{
  int x=10;
  m(out x);
Response.write(x);
 }
public void m(out int x)
   {
       // must be declare variable (without variable it will be showing error)
   }
}
output: showing error  if u suppose declare some variable value then its ok.but in case of ref keyword no need to declare variable value.

No comments:

Post a Comment