0

I do not get a potential virtual function call in constructor warning when I do:

   public abstract class B : A
    {
        protected B(IEngine engine) : base(engine)
        {
            C = new C(CanExecuteChange);
        }

        public C C{ get; }
        public abstract bool CanExecuteChange();
    }

Where class C's constructor takes a Func<bool>

But CanExecuteChange might be virtual? So couldn't we be calling a virtual function in the constructor?

juharr
  • 31,741
  • 4
  • 58
  • 93
jmasterx
  • 52,639
  • 96
  • 311
  • 557
  • `But CanExecuteChange might be virtual` how do you foresee that? – Jonesopolis Sep 14 '16 at 18:07
  • 1
    I think it's just a case of Resharper not going out of it's way to find this potential issue since the method is not actually called directly inside of the constructor. – juharr Sep 14 '16 at 18:07
  • 1
    @Jonesopolis Well, it's `abstract`. All `abstract` methods are, by definition, implicitly `virtual`. – Servy Sep 14 '16 at 18:08
  • Are you 100% sure that C# is language you are using? Because unlike C++ there is no* problems calling virtual functions from constructor in C# (* - ok it will likely behave badly too but in well-defined way unlike C++ - http://stackoverflow.com/questions/119506/virtual-member-call-in-a-constructor) – Alexei Levenkov Sep 14 '16 at 18:47
  • Are you expecting a compiler warning or something like a resharper warning? Perhaps you should explain why you think it *should* be giving you a warning? – Chris Sep 14 '16 at 21:33

1 Answers1

2

Just because you're passing CanExecuteChange to another method, doesn't mean it's actually being called. If your code looks like this:

public class C
{
    private Func<bool> _func;

    public C(Func<bool> func)
    {
        _func = func;
    }
}

then the ctor of C is just storing the passed-in Func for later and there's nothing to worry about.

Even if the C ctor does invoke the passed Func:

public class C
{
    public C(Func<bool> func)
    {
        Console.WriteLine(func());
    }
}

R# necessarily has a finite limit on how deep it will look and will not flag this.

AakashM
  • 62,551
  • 17
  • 151
  • 186