Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Tuesday, 11 October 2011

Difference Between Ref and Out In C#

The out and the ref parameters are used to return values in the same variables, that you pass as an argument of a method. These both parameters are very useful when your method needs to return more than one values.

  • ref = Reference, when parsed to a method, the method references that original variable and doesn't create another instance. So if you make a change to a var parsed into that method when ref is used, it will affect the calling method

  • out = Out is a little different in that you can return more than one value from a method (apart from a return )


Difference?

- A variable to be sent as ref parameter must be initialized.
It is intended to be changed in the method to which it is passed.

- A variable to be sent as out parameter don't need to be initialized
before being passed to a method, because it must be assigned in that method.
It is not intended to be changed, but intended to be assigned(or reassigned)
in the method to which it is passed.

- A "ref" parameters need initialization BEFORE you call the function; "out"
does not.

The following will not compile:
string a;
f(ref a);

The following will compile:
string a;
g(out a);

Decription:
The out Parameter:
The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.

public class mathClass

{

public static int TestOut(out int iVal1, out int iVal2)

{

iVal1 = 10;

iVal2 = 20;

return 0;

}

public static void Main()

{

int i, j; // variable need not be initialized

Console.WriteLine(TestOut(out i, out j));

Console.WriteLine(i);

Console.WriteLine(j);

}

}

The ref parameter:
The ref keyword on a method parameter causes a method to refer to the same variable that was passed as an input parameter for the same method. If you do any changes to the variable, they will be reflected in the variable.
You can even use ref for more than one method parameters.


public class myClass

{

public static void RefTest(ref int iVal1 )

{

iVal1 += 2;

}

public static void Main()

{

int i; // variable need to be initialized

i = 3;

RefTest(ref i );

Console.WriteLine(i);
}
}

Thanks Happy Coding :)


References
  1. http://www.dotnetobject.com/showthread.php?tid=171
  2. http://www.c-sharpcorner.com/UploadFile/mahesh/out_and_ref11112005002102AM/out_and_ref.aspx

Tuesday, 13 September 2011

What Is Interface And Why We Use It?

Interface is simply like a class in OOP(Object Oriented Programming)In which we only declare the functions, properties, events and indexers but not defined that.Interface cannot contain fields. Implementation of all members (functions, properties, events and indexers) of interface must be given in a class which is derived from it.
Very common question is that why we use interface? Answered after some examples so it is more understandable.

Sample Example of Interface:

public interface IA
{
void Add();
int Count { get; }
event MYEvent Changed;
string this[int index] { get; set; }
}

Point to be noted that that there is no access modifies in any of the function or other members of interface in above example. Because declaring member in interface must be without access modifier and when we implement these members in derived class they all must declare as a public otherwise compile error occurs.

Complete Sample Example:

interface IA
{
void Method1();                     //Declare function without definition
void Method2(int i);                //Declare function without definition
}

class Implement_IA : IA       //Derived class of IA so it must implemts all members of interface IA
{
public void Method1()            //Implement method1 of IA must be public
{//....Do Some Work} 

public void Method2(int i)       //Implement method2 of IA must be public
{ //....Do Some Work }

public void ClassOwnMethod(string str)   //This is class own method
{ //....Do Some Work} 

}
public static void Main()
{

//Use of Methods is normal as we use

Implement_IA obj = new Implement_IA ();
obj.ClassOwnMethod("String");
obj.Method1();
obj.Method2(10);
}

In above example we made interface “IA” declare two methods,One class “Implement_IA ” inherit from “IA” and implements methods of interface and contain one its own method.

Why we use interface and purpose of interface?

Now come to question what is the purpose of interface and why we use it.
It is understand by the following phenomenon: 

Human beings have same structure of skeleton. But Outer Covering is different of each human. So consider skeleton as an interface and Outer Covering as class .All Outer Covering of human beings (Classes) inherits from same skeleton (Interface) and implement different functionalities according to that each human is differen from other.
Similarly all types of horses has same skeleton (Interface) but each horse is different from another on the basis of colour,cast etc same as defined above.

So this is the purpose of interface that it provides the structure of a scenario. For example we have to make method of numeric series so we made interface and declare method of series. Now if  we want series of numbers odd, even, multiple of 3, Etc. we implement the same method with different implementation according to type of series. 

Here is one Example:

interface IAnimal
{
void speak();
}
class Cow : IAnimal
{
public void speak()
{      //Implementation of Speak according to Cow           }
}
class Horse : IAnimal
public void speak() 
{       //Implementation of Speak according to Horse       }
}
public static void Main()
{
Cow objCow = new Cow();
Horse objHorse = new Horse();

//Calling same function with different implementations

objCow.speak();
objHorse.speak();
}

So in above example “Speak” function is implementing two times one for “Horse” and one for “Cow”. It can be say that Interfaces have no work without Class or Structure. 
Take a look diagrammatically

Now hope you understand why we use interfaces and what the purpose of it.

FAQ:

1) Can we create object of interface?

No! Object of interface cannot be created because it is only structure it has no implementation of anything only declaration, Second it has no constructor as well so it cannot be instantiate.
However we made object of interface by instantiating it to the derived class
Example 

Interface IA{ }

Class B:IA{ }

Main()
{
IA obj=new B();
//or
B objB=new B();
IA obj=objB;
}

2) Can Interface derived from other interface?

Yes! Inheritance between interfaces is allowed

Example:

Interface IA{ }
Interface IB:IA{ } 
However when class derived from interface “IB” so it must give implementation of “IA” and “IB” both.

3) How implement Multiple Inheritance in interfaces?

Multiple inheritances is allowed in Interfaces in C#

For example:

Interface IA{ }
Interface IB { } 

Class MyClass:IA,IB //here we inherit class from two interfaces
{
//Class must implement both interfaces IA and IB
}

Please feel free to ask.
Any corrections must be appreciable.
Thank You
hope it helps!

Happy Coding :)