4

Possible Duplicate:
C# optional parameters on overridden methods

using System;
namespace Apple
{
    class A
    { 
        public virtual void Func(int a=4){
            Console.WriteLine(" A Class: "+a);
        }
    }
    class B : A
    {
        public override void Func(int a = 12)
        {
            Console.WriteLine(" B Class: "+ a);
        }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            A ob = new B();
            ob.Func();
            Console.ReadLine();
        }
    }
}
// Output: B Class: 4
Community
  • 1
  • 1
A.T.
  • 24,694
  • 8
  • 47
  • 65

4 Answers4

2

Default parameters are filled at compile time, and the code references a variable ob through the base class. The virtual method override works at run time, as expected. You could achieve the desired effect by using method overload:

class A 
{
   public void Func(int value) 
   {

   }

   public virtual void Func() 
   {
        Func(4);
   }
}

class B: A
{
   public override void Func() 
   {
        Func(12);
   }
}
alexm
  • 6,854
  • 20
  • 24
1

The compiler places the the default parameter value based on the type of the object and is done during the compile time.
Hence the compiled code would look like:

using System;
namespace Apple
{
    public class Program
    {
        private static void Main(string[] args)
        {
            A ob = new B();
            ob.Func(4);
            Console.ReadLine();
        }
    }
}


You could get the desired result by doing this:

public class Program
    {
        static void Main(string[] args)
        {
            A ob = new B();
            ((B)ob).Func();
            Console.ReadLine();
        }
    }
coder_bro
  • 10,503
  • 13
  • 56
  • 88
0

Because you creating instance of Class A which is referring to the address of class B.

A ob = new B();

Since the instance is of class A, the method you calling is pointing to method in class A. You can check this by putting debug and then execute the code.

instead if you create instance of class B ie

B ob = new B();

it will call the method Fun() from class B and will display output as " B Class: 12"

Anup
  • 80
  • 1
  • 1
  • 6
  • ob is just a reference to the base class, it holds actually instance of the B class, it is the concept of dynamic dispatching. – A.T. Dec 27 '12 at 06:35
0

the default parameter value is Static binding.

pthread
  • 35
  • 5