delegates and virtual functions

P

puzzlecracker

Do delegates don't respect polymorphisms -- why?

say in this example:

using System;

public delegate string FirstDelegate (int x);


abstract class Base
{
public abstract string Foo(int );

public void Dispatch()
{
FirstDelegate del=new FirstDelegate (Foo);
del(5);
}
}



class Derived
{
public override string Foo(int x)
{
return " "+x;
}
}


class Runner
{

public static void Main()
{
Derived d=new Derived();
d.Dispatch(); //trys to delegate bases
}
}


The same thing happens when Base is NOT abstract class and Foo is
declared as virtual....

Is there a rule don't mix delegates and runtime polymorphism???
 
P

Philipp Brune

Hi,

why should delegates not respect polymorphisms ?
This code, works as expected for me. FirstDelegate
points to the implementation of Foo(..) in Derived.
The only thing that leads to a StackOverflowException is
doing

class DerivedOverflow : Derived
{
public override string Foo(int x)
{
return "-" + base.Dispatch();
}
}

which is also expected behaviour from my understandings.

Perhaps you could explain a little more what you mean.

Philipp
 
M

Marc Gravell

What same thing? Unfortunately, you haven't pasted the exact code [it
doesn't compile...], so we can't know what you are seeing, since any
repairs we make may change the problem...

However, making the most obvious fixes (adding a base class, naming
the argument, etc) - it all works fine and the override in Derived is
called.

Delegates respect polymorphism.

Perhaps tell us what you are seeing?

Marc
[C# MVP]
 
P

puzzlecracker

Hi,

why should delegates not respect polymorphisms ?
This code, works as expected for me. FirstDelegate
points to the implementation of Foo(..) in Derived.
The only thing that leads to a StackOverflowException is
doing

  class DerivedOverflow : Derived
     {
         public override string Foo(int x)
         {
             return "-" + base.Dispatch();
         }
     }

which is also expected behaviour from my understandings.

Perhaps you could explain a little more what you mean.

Philipp

Great! let me get the debug, i thing my telling compiler to think
Base is Base.....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top