Given this situation:
interface Interfaz
{
void M1();
}
abstract class ClaseAbstracta : Interfaz
{
public void M1() { }
public abstract Boolean M2();
}
class ClaseConcreta : ClaseAbstracta
{
public override Boolean M2() { return false; }
public virtual void M3(Int32 i) { }
public void M4() { }
}
I also do:
ClaseConcreta concretaCast = (ClaseConcreta) abst;
Could concretaCast.M2() be analysed statically?
For one, it has override so it seems as it couldn't but when you see M2() it actually is the concrete implementation.
So is this statically analyzable or every time it has override it has to do it during run-time dynamically?
I doubt that this can be statically analyzed in the general case. Consider:
class ClaseConcreta2 : ClaseConcreta
{
public override Boolean M2() { return true; }
}
void Main()
{
var x = new ClaseConcreta2();
DoSomething(x);
}
void DoSomething(ClassAbstracta abst)
{
ClaseConcreta concretaCast = (ClaseConcreta) abst;
// okay, so it's a ClaseConcreta, but what kind?
}
It could be sometimes:
void DoNothingReally(ClaseAbstracta x)
{
ClaseConcreta y = new ClaseConcreta();
y.M2(); // Only possibly the implementation from ClaseConcreta.
ClaseAbstracta abst = y;
ClaseConcreta concretaCast = (ClaseConcreta) abst;
concretaCast.M2(); // Only possibly the implemenation from ClaseConcreta, but more work to figure this out.
x.M2(); // can't know where the implentation is from generally, but see below
}
void DoMoreNothing()
{
DoNothingReally(new ClaseConcreta());//the call x.M2() above will only possibly the implemenation from ClaseConcreta but lots of work to figure that out.
}
Now, another question is whether anything actually will determine this. In writing about C++, Bjarne Stroustrup talks about the fact that compilers can replace virtual calls with non-virtual calls as an optimisation. I've no idea how much that is done in C++, never mind if anything does it with C#. It is theoretically possible though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With