c# - Need to run a protected method when my class is instantiated -


i have base class custom attributes, class base class many other clases class:

[customattribute1("first")] [customattribute2("other")] public class foo {     protected void checkattributes()     {         // need run code when class , derived classes instantiated      } } 

then if créate instance

foo myclass = new foo(); 

or build dereived class:

[customattribute1("firstderived")] public custclass : foo {     public custclass(int myvar)     {         //something here     }     public void othermethod()     {     } }  custclass myclass = new custclass(5); 

i need method checkattributes() allways run.

is posible?

there aproach ?

note: need shure checkattributes() runs if in derived classes constructor redefined:

yes, define constructor calls method:

public class foo {     public foo()     {         checkattributes();     }      protected void checkattributes()     {         throw new notimplementedexception();     } } 

as long every constructor on foo winds calling checkattributes() (either directly or chaining constructor does) derived classes not able avoid check.

(it's unclear why method protected, though. consider making private, sounds one-time check run when object constructed, , shouldn't need run later.)


one of foo's constructors must called (directly or indirectly) type derives foo (directly or indirectly).

from section 10.11.1 of c# 5 language specification:

all instance constructors (except class object) implicitly include invocation of instance constructor before constructor-body.

...

if instance constructor has no constructor initializer, constructor initializer of form base() implicitly provided.

the only way derived type can avoid calling constructor on foo infinitely recurse 1 of own constructors, lead stackoverflowexception.


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -