Archive for category Versus (vs)
Difference between ‘Shadowing’ and ‘Overriding’ (Shadowing vs Overriding) – C#
Posted by Rajanihanth in .Net, C#, Tech Tips-.Net, Versus (vs) on July 29, 2012
This is a very quick Tech-Tips..! Actually Shadowing is VB.Net concept, in C# this concept called hiding! We will see this chapter later. 🙂
Shadowing : Creating an entirely new method with the same signature as one in a base class.
Overriding: Redefining an existing method on a base class.
- Both are used when a derived class inherits from a base class
- Both redefine one or more of the base class elements in the derived class
If you want to read more regarding this, just follow this MSDN topic.
class A { public int M1() { return 1; } public virtual int M2() { return 1; } } class B : A { public new int M1() { return 2; } public override int M2() { return 2; } } class Program { static void Main(string[] args) { B b = new B(); A a = (A)b; Console.WriteLine(a.M1()); //Base Method Console.WriteLine(a.M2()); //Override Method Console.WriteLine(b.M1()); Console.WriteLine(b.M2()); Console.Read(); } }
The output is : 1, 2, 2, 2
Difference between ‘ref’ and ‘out’ parameters (ref vs out) – C#
Posted by Rajanihanth in .Net, Tech Tips-.Net, Versus (vs) on July 14, 2012
- Both are treated differently @ runtime but same in the compile time, so can’t be overloaded.
- Both are passed by references except ‘ref’ requires that the variable to be initialized before passed.
ref:
class Program { static void M1(out int i) { i = 1; i += 1; } static void Main(string[] args) { int j; //Not assigned M1(out j); Console.Write(j); Console.Read(); } } }
The output is : 2
out:
class Program { static void M1(ref int i) { i = 1; i += 1; } static void Main(string[] args) { int j=0; //Assigned M1(ref j); Console.Write(j); Console.Read(); } }
The output is same: 2, but we have to assigned the variable before used otherwise we will get an error.