Here's a cool features of the .Net Framework 2.0 that I think isn't too widely known.
Did you know that you can have a public property but restrict the Set portion of it as Protected? That gives the developer an extra level of control so that derived classes have the ability to set the property's value but other classes can only get the property's value. Check out this sample:
public class BaseClass { private string _myValue; public string MyValue { get { return _myValue; } //NOTE THE SET IS PROTECTED! protected set { _myValue = value; } } } public class ExtendedClass : BaseClass { public void DoSomething() { MyValue = "some value"; string s1 = MyValue; } } public class DifferentClass { public void DoSomething() { BaseClass b = new BaseClass(); string s = b.MyValue; b.MyValue = "some value"; //THIS GETS A COMPILER ERROR! } }
You can see that in ExtendedClass I can use the property to GET or SET, but in DifferentClass I can only GET.
Here is the error that Visual Studio reports:
I should mention that Intellisense did not show this error (with the squiggly lines) instantly as it usually does. I needed to compile the project before Visual Studio recognized something was wrong. And in case you are wondering...Yes, this feature is included in VB.Net too. Although I should mention that in VB.Net, Intellisense showed me the error even before I compiled. Darn, I hate to say nice things about VB.Net. Here is a VB.Net version:
Public Class BaseClass Private _myValue As String Public Property MyValue() As String Get Return _myValue End Get Protected Set(ByVal Value As String) _myValue = Value End Set End Property End Class Public Class ExtendedClass Inherits BaseClass Sub DoSomething() Dim s1 = MyValue 'GET WORKS MyValue = "Some Value" 'SET WORKS End Sub End Class Public Class DifferentClass Sub DoSomething() Dim b As New BaseClass Dim s1 As String s1 = b.MyValue 'GET WORKS b.MyValue = "Some Value" 'SET GETS A COMPILER ERROR!!!! End Sub End Class
Hopefully this is helpful to you!
Remember Me
.Net (37) asp.net (7) Ben (12) Blog (6) Code Camp (26) Entertainment (2) Family (14) Fun Stuff (4) General (17) Hiking (1) LINQ (1) Microsoft (9) Movies (2) NoDeNUG.org (3) Orbius (2) Philly.Net (46) SQL Server (3) Tech-Ed 2007 (3) Technology (21) Travel (1) Vista (7) Web (8)
Powered by: newtelligence dasBlog 1.9.6264.0
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2008, Andrew Schwam
E-mail