D
D
Denis Bredun2020-07-15 21:19:28
C++ / C#
Denis Bredun, 2020-07-15 21:19:28

How is a hidden method called under the hood?

I know how virtual methods are called under the hood, but I did not find any information from Goldstein or Richter about how a hidden method is called. So how does this even happen? Help me please.
That is, how this method is called:

class A
{
 public void DoSmth()
 {

 }
}
class B : A
{
 public new void DoSmth()
 {

 }
}
class Program
{
 public static void Main()
 {
  A a = new B();
  a.DoSmth();
 }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
ayazer, 2020-07-16
@Luffy1

and it shouldn't be in the books. you are now asking about implementation details, which even within the .net framework may differ (.no, it's not just c#). Usually, for such knowledge, you need to climb specifically into the guts of the compiler / runtime. But remember that knowledge of a few principles replaces knowledge of many nuances, and usually understanding "how it usually works" is enough.
and answering this question specifically - which method to call is determined in runtime based on the information in the virtual table which is corresponding. class. And Richter definitely mentions this (that calling a virtual method is somewhat slower because you have to do an additional check on the virtual table to understand what exactly needs to be called).
In general, it goes +- like this:
1. a virtual table is created for each class a la [method_id address ...]
Class1:
0x001 0x0001 ...
0x002 0x0100 ...
...
Class2:
0x002 0x0F00 ...
...
2. when you do instanceOfMyClass. DoSomethingUsefull(...) The CLR checks the virtual table (perhaps it runs through the entire inheritance hierarchy to understand exactly where the required method lies) and then calls it by passing it the address where the class itself is stored in memory AND the list of parameters with which the method is called.
^ I can be wrong in the nuances, but the principle is

V
Vladimir Korotenko, 2020-07-15
@firedragon

If I understand the question correctly, then something like this.
In general, use documented functions and public methods.

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, 
    BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(this, new object[] { methodParams });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question