In my ASP.Net MasterPage I sometimes have controls that need to be accessed by most Pages.
Now instead of using this to access the control
((Label)this.Page.Master.FindControl("lblBreadCrumb")).Text = "foo";
I tend to put a Property in the MasterPage with a reference to the Control, set the @MasterType directive in the Page and access the control like this:
this.Master.BreadCrumb.Text = "foo";
I find this approach much easier to use, but I never actually saw someone do it like this so I wonder if there is any good reason against it that I am missing?
Using properties is a much better idea than using
FindControlfor several reasons, I’m glad that you’re using this approach!The most compelling reason to use properties is lets say you change the name of a control, or remove it all together. Now, you have a compiler error, which is much easier to spot. For example, if you rename
lblBreadCrumband you’re usingFindControl, the compiler will not catch this error, and instead your app will fail at run time. Catching errors at compile time is a great feature of a language.The reason why you don’t see many other developers doing this is because good OO design is hardly ever found in Web Forms unfortunately.