out and ref keywords in C#

As we already studied about  CALL BY REFERENCE  in C of our academic period.

In call by reference , we passed the address of that variable's value to method.

But due to point died in C# , we used REF  keywords in C#.

REF :

   Ref parameters are changed at the calling site. They are passed as references, not values. This means you can assign the parameter in the called method and have it also be assigned at the calling site.

  • There is a big difference between ref and out parameters at the language level. Before you can pass a ref parameter, you must assign it to a value.
  • This is for the purpose of definite assignment analysis.
  • You don't need to assign an out parameter before passing it to a method. The compiler allows this.
Sample program for understanding :

 
 public static void Main(string[] args)
{         int val = 1;
Method (ref  val);Connsole.WriteLine("By ref keyword :{0}" ,val); Console.ReadLine();
}

static void Method(ref int i)
{           
     i = i + 44;
}

Output :
By ref keyword : 45




Out :
  Outsignifies a reference parameter. Sometimes methods must return more than one value and not store class state. Out fills these requirements. With it we pass parameters whose changes are realized in their calling methods.

Sample program for understanding :

public static void Main(string[] args)
{bool period;
bool comma;
bool semicolon;
const string value = "has period, comma.";
TestString(value, out period);
Console.WriteLine(value);
Console.Write("period: ");
Console.WriteLine(period);
}

static void TestString(string value, out bool period)
{
period = comma = semicolon = false;for (int i = 0; i < value.Length; i++)
{switch (value[i])
{case '.':
{
period = true;
break;
} 
}

}

}


Enjoy...!! Please suggest correction if requried ..!!

 

Comments

Popular posts from this blog

Add Serial no in crystal report without coding

File operations in C# (.net)

SQL – Generate decimal numbers sequence for particular number range