Friday, August 03, 2007
« Philly.Net News 7/31/2007 | Main | I hate TrustedInstaller! »

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:

PropertyError

 

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!

Thursday, September 25, 2008 3:37:00 AM (Eastern Standard Time, UTC-05:00)
Thanks for sharing, Very cool feature! Just stumbled accross the featrue in an ex-empoyee's code that I have to take on and was wanderign what it was all about.
Steve
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):