MichaelK
MichaelK

Reputation: 3

Passing in member functions as delegate parameters

I have a base class, whose ctor takes a delegate as a parameter and a class which inherits from it.

The following works just fine:

class Base
{
    public Base(Func<bool> func)
    {
    }
}

class Sub : Base
{
    public Sub()
        : base(() => true)
    {
    }

    public Sub(int i)
        : base(() => { return true; })
    {
    }
}

How can I pass an instance function as a parameter? Compiler complains with error "An object reference is required for the non-static field, method, or property".

What I would like to have is this:

class Sub : Base
{
    public Sub()
        : base(Func)
    {
    }

    private bool Func()
    {
        return true;
    }
}

It would work if Func was a static method. But I'd like to use instance members inside the function.

How could I accomplish this?

Upvotes: 0

Views: 437

Answers (1)

Boo
Boo

Reputation: 673

As commented this looks to me like an X Y problem to me, and seems like a flawed design, can you change your base class to just call a virtual method and just override it ?

class Base
{
    public Base()
    {
    }

   public virtual bool func() {return false};
}   

class Sub : Base
{
  public Sub()
  {
  }

  public override bool func()
  {
    return true;
  }
}

also you can read more about it at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual

Upvotes: 2

Related Questions