inheritance and static

  • Thread starter Thread starter Adam Klobukowski
  • Start date Start date
A

Adam Klobukowski

Consider following example:

class A
{
public static Method()
{
/* ... */
}
}

class B : A
{
}

How can i chcek in Method() if it was called as B.Method() or A.Method()?
 
Maybe like this:

class testA
{
public void Method()
{System.Windows.Forms.MessageBox.Show(this.ToString());}
}


class testB : testA
{
}

testA local_A = new testA();
local_A.Method();

testB local_B = new testB();
local_B.Method();

Frank Uray
 
Adam Klobukowski said:
Consider following example:

class A
{
public static Method()
{
/* ... */
}
}

class B : A
{
}

How can i chcek in Method() if it was called as B.Method() or A.Method()?
class A {

public static void M() { M(false); }

protected static void M(bool derived){/* the biz */}}

class B : A{new static void M(){A.M(true);}}
 
Hi,

Remember that the entire point of the question was the fact that Method was
static
 
Hi,

Frankly I do not think you can tell, either B.Method or A.Method should
gets resolve at compile time to call the correct method.

Why you need to know that?
 
Ignacio Machin ( .NET/ C# MVP ) napisa³(a):
Hi,

Frankly I do not think you can tell, either B.Method or A.Method should
gets resolve at compile time to call the correct method.

Why you need to know that?

Well, the whole idea seems to be flawed end will be redone in some other
way. The point was to be able to have a static function in class that
could beahave in different manner, dependint on classes that inherit
from it.
 
Hi,


Well, the whole idea seems to be flawed end will be redone in some other
way. The point was to be able to have a static function in class that
could beahave in different manner, dependint on classes that inherit from
it.

What you want is a virtual method.

Also take a look at the singleton pattern, maybe you want something like
that.
 
Well, the whole idea seems to be flawed end will be redone in some other
way. The point was to be able to have a static function in class that
could beahave in different manner, dependint on classes that inherit
from it.

Yeah, the base class knows nothing about derived classes. Derived classes
will need to implement their specific functionality. It's very difficult to
break polymorphism, but it's always fun to try.
 
Not really an answer, but I had a similar question on an interview ...
and the solution I came up with was to throw an exception in the static
method and walk the stack trace to find the class making the call.
 
John Murray said:
Not really an answer, but I had a similar question on an interview ...
and the solution I came up with was to throw an exception in the static
method and walk the stack trace to find the class making the call.

That's not reliable - it could be misled by inlining, for instance.

The real solution is not to use a design which goes against the
language and platform idioms.
 
Back
Top