1A. Difference between out and ref parameters?
- ref and out both are used for passing parameters by reference instead of value.
- You need to initialize the variable before passing in the case of ref.
- In C# a variable must be initialized before it is used even in case of pass by value.
- To give an extra advantage to reference parameters, out is introduced where we don't need to initialize.
- One more difference between ref and out is that in out u need to assign the value inside the function before returning otherwise it will give a compilation error. But in the case of ref, there is no such restriction.
- Code reusability and hence less code.
- Type safety and hence we can resolve run time exceptions in compile-time only.
- no Typecasting and hence better performance.
public static void main
{
int i = 100; // Initialized before passing
Add(ref i );
Console.Writeline(i);
}
static void Add(ref int i)
{
i = i + 10;
}
public static void main
{
int i ; // no need to initialize before passing
Add(out i );
Console.Writeline(i);
}
static void Add(out int i)
{
i = i + 10;
}
1B. Difference between the object as parameter and ref parameters?
If we use the ref keyword for the object, then it is going to create a new object and return that object.
Here if you write Console.WriteLine(test.Name);
it is going to return Director.
Now remove ref and call the method, it is going to return "actor".
If we use the ref keyword for the object, then it is going to create a new object and return that object.
Here if you write Console.WriteLine(test.Name);
it is going to return Director.
Now remove ref and call the method, it is going to return "actor".
No comments:
Post a Comment