Tuesday, 26 July 2016

ref and out keyword

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

Program with ref and out keyword

  1. public class Example
  2. {
  3. public static void Main() //calling method
  4. {
  5. int val1 = 0; //must be initialized
  6. int val2; //optional
  7.  
  8. Example1(ref val1);
  9. Console.WriteLine(val1); // val1=1
  10.  
  11. Example2(out val2);
  12. Console.WriteLine(val2); // val2=2
  13. }
  14.  
  15. static void Example1(ref int value) //called method
  16. {
  17. value = 1;
  18. }
  19. static void Example2(out int value) //called method
  20. {
  21. value = 2; //must be initialized
  22. }
  23. }
  24.  
  25. /* Output
  26. 1
  27. 2
  28. */

Note

  1. Do not be confused with the concept of passing by reference and the concept of reference type. These two concepts are not the same.
  2. A value type or a reference type can be passed to method parameter by using ref keyword. There is no boxing of a value type when it is passed by reference.
  3. Properties cannot be passed to ref or out parameters since internally they are functions and not members/variables.

Ref and out in method overloading

Both ref and out cannot be used in method overloading simultaneously. However, ref and out are treated differently at run-time but they are treated same at compile time (CLR doesn't differentiates between the two while it created IL for ref and out). Hence methods cannot be overloaded when one method takes a ref parameter and other method takes an out parameter. The following two methods are identical in terms of compilation.
  1. class MyClass
  2. {
  3. public void Method(out int a) // compiler error “cannot define overloaded”
  4. {
  5. // method that differ only on ref and out"
  6. }
  7. public void Method(ref int a)
  8. {
  9. // method that differ only on ref and out"
  10. }
  11. }
However, method overloading can be done, if one method takes a ref or out argument and the other method takes simple argument. The following example is perfectly valid to be overloaded.
  1. class MyClass
  2. {
  3. public void Method(int a)
  4. {
  5.  
  6. }
  7. public void Method(out int a)
  8. {
  9. // method differ in signature.
  10. }
  11. }
OR,

Out and Ref are C# keywords which helps to pass variables in methods and functions as REFERENCE types. Out is one way and Ref is two way.
Let us try to understand the above sentence. Below is a simple function "SomeFunction" which takes a variable "InsideVar".
Now assume there is a caller who calls the above method as shown in the below code. After the call is made to "SomeFunction" , "OutSideVar" variable is not modified. In other words by default values are passed to methods and function BY VAL.
Now let us apply REF keyword to the method variable as shown in the below code.
If you decorate method variables using REF you also need to provide REF keyword in the caller as shown in the below code. Now in this situation the output of "OutSideVar"  will be "30". In other words the variable is passed by reference. Any modification to the REF variables inside the methods and function will be affected to outside variables as well.
OUT is same like REF keyword ,  it also passes variables by reference but the OUT variables compulsorily needs to be initialized inside the methods and functions.
Which means when the caller passes data to a method which is having OUT variables those data will be discarded. In the below case "20" value is passed from the caller but this data will be discarded as the OUT variables will be initialized again inside the method / function.
So lets summarize so that interviewer does not take us for a ride:- 
  • OUT and REF helps to pass variables BY REFERENCE.
  • In OUT we need to compulsorily initialize variables inside the function for REF we do not need to do the same.
  • REF helps to pass data two ways i.e. from caller to callee and back. While OUT is one way it just passes data from callee to caller.


Saturday, 23 July 2016

What is Delegate

What is Delegate-

Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.

Syntax of Delegate & Methods Declaration

Check below sample code for delegate declaration and methods declaration


public delegate int Delegatmethod(int a,int b);

public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x + y;
}
}
If you observe above code I declared Delegatmethod method with two parameters which matching with methods declared in Sampleclass class.

Complete Example


public delegate int DelegatSample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();

DelegatSample delgate1 = sc.Add;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2 = sc.Sub;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}
Output

Whenever we run above code we will get output like as shown below-

Add Result : 30
Sub Result : 1

What is the use of Delegates?

Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.

Delegates are two types

      -   Single Cast Delegates
      -  Multi Cast Delegates

Single Cast Delegates

Single cast delegate means which hold address of single method like as explained in above example.

Multicast Delegates

Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list

Check below sample code for delegate declaration and methods declaration

Syntax of Multicast Delegate & Method Declaration

Check below sample code for multicast delegate declaration and methods declaration


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
If you observe above code I declared MultiDelegate method with void return type.

Complete Example


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
Output

Whenever we run above code we will get output like as shown below


Addition Value : 15
Subtraction Value : 5
Multiply Value : 50