1

I am wondering if an overridden OnApplyTemplate method can be called before the non-static constructor of the Control is called?

I am currently investigating possible NullReferenceException sources and was wondering if such scenario could be the cause of it, thanks.

Nikita Shrivastava
  • 2,978
  • 10
  • 20
Vladimir Amiorkov
  • 2,652
  • 3
  • 17
  • 35
  • why do you want to do so?? logically first you will create an object then you would want it to render it. – Nikita Shrivastava Sep 24 '15 at 07:19
  • 1
    The answer is: nope, it can't. It's a method of a class instance. Without instance created you can't call it's method. – netaholic Sep 24 '15 at 07:26
  • 1
    @netaholic It's technically well possible that the base class constructor calls the method. But it is bad practice to call virtual methods in constructors, and I'm sure WPF won't do it. – Clemens Sep 24 '15 at 07:32
  • @Clemens Good point, I've missed it – netaholic Sep 24 '15 at 07:35
  • Thank you for all your answers. @Clemens what about in Silverlight, I know there are quite a few funky things in SL that are totally opposite from what they are in WPF. – Vladimir Amiorkov Sep 24 '15 at 07:37
  • You should be able to set some breakpoints, in your constructor and in an overridden OnApplyTemplate method. – Clemens Sep 24 '15 at 07:40
  • @Clemens Yes I am and the expected is observed. The call stack both in WPF and SL is the following: Static Constructor > Constructor > OnApplyTemplate This is totally ok and does not lead to an NullReferenceException. but my users are reporting that they do see an exception and want me to perform "defensive programming" in such cases. As I do not want to blindly do things I am interested in seeing of such "defensive programming" is required in such scenarios. – Vladimir Amiorkov Sep 24 '15 at 07:44

0 Answers0