2

Possible Duplicate:
Overload resolution and virtual methods

If i call this , why object method is being called?

Classes.Class2 c = new Classes.Class2();
c.GetJ(1);

public class Class1
{
   public virtual void GetJ(int j)
   {

   }
}

class Class2:Class1
{
    public override void GetJ(int j)
    {
       int j3 = 8;
    }

     public void GetJ(object j)
     {
        int j1 = 82;
     }
}
Community
  • 1
  • 1
Charu
  • 2,679
  • 6
  • 35
  • 52
  • 1
    A really interesting question. The duplicate (linked above) has a bit more complex code as they didn't use built in types, but it's exactly the same behaviour. Look specifically at @EricLipperts answer. – Anders Abel Jul 31 '12 at 08:35
  • @Anders Abel : Thanks for your link. Eric Lippert's comment is indeed enlightning. – paercebal Jul 31 '12 at 08:46

2 Answers2

1

See the C# 4.0 Specification ( https://www.microsoft.com/en-us/download/details.aspx?id=7029 )

7.4 Member lookup

First, a set of accessible members named N is determined:

  • If T is a type parameter, then the set is the union of the sets of accessible members named N in each of the types specified as a primary constraint or secondary constraint (§10.1.5) for T, along with the set of accessible members named N in object.

  • Otherwise, the set consists of all accessible (§3.5) members named N in T, including inherited members and the accessible members named N in object. If T is a constructed type, the set of members is obtained by substituting type arguments as described in §10.3.2. Members that include an override modifier are excluded from the set.

I don't understand that behavior, but this is in the specification, so it is correct, even if a bit disturbing (and I have a C++ background)...

Edit:

This is indeed a duplicate question (as correctly discovered by Anders Abel in his comment).

See the original Overload resolution and virtual methods for an explanation for this behavior.

Community
  • 1
  • 1
paercebal
  • 81,378
  • 38
  • 130
  • 159
0

This method

public void GetJ(object j)
{
    int j1 = 82;
}

is hiding the inherited GetJ(int j) because (and that's just how things work, there isn't much that can be done aside being more explicit in which method one intends to invoke) overrides are never used when there is an applicable non-overridden method in the same scope. So basically ... your code works as intended.

Alex
  • 23,004
  • 4
  • 39
  • 73
  • `both the IDE and the compiler should be issuing a Warning about this` : Tried it on Visual C++ 2010, vanilla install. – paercebal Jul 31 '12 at 08:34
  • Now I had some coffee , turned on my brain, I'm editing this (because it is obviously off the point) – Alex Jul 31 '12 at 08:38