0

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?

4
  • 4
    this looks to me like an X Y problem to me, can you change your base class to just call a virtual method and just override it ? Commented Jun 26, 2018 at 14:16
  • @Boo That's an answer I would upvote... (hint hint!) Commented Jun 26, 2018 at 14:18
  • @Boo That assumes that the delegate must be an instance method, rather than simply allowing it to be an instance method (or anything else). Commented Jun 26, 2018 at 14:21
  • @Boo I guess that would work. I was so focused on delegates that I totally forgot about virtual or even abstract methods. Commented Jun 26, 2018 at 14:24

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah I think that's the way to go. Thanks.
If you want to also be able to put an arbitrary delegate in from the outside, you could have a property like Func<bool> FuncProp that either stores the given delegate or if non is given refers to the func() method. And then use that property wherever needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.