The World According to Nick
Politics, News, Photography, and Triathlons... What don't I talk about?
Tuesday, March 02, 2004
<< How Fast is Fast Enough? Kerry Not Representing Anyone >>
Is a Property a Field or Function?
I've been reading a book called The Elegant Universe lately... talking about fun things like String Theory, Hidden Dimensions, Theory of Everything... etc. You know light reading. One of the things being discussed in the book right now is the dual nature of light. The fact that it acts as both a wave and a particle. What does this have to do with properties in .NET you ask? Like light, properties are a funky little thing. They're syntacticly like a field. But their underlying implementation is a pair of functions. In essense, a property is a field where the programmer is allowed to do extra type checking, and validation... abstracting away those details so the consumer of the property doesn't even need to know thats happening. A programmer could even create a property called Age, but never store the age in the object. Instead, he might track the birth date, and return the age each time by doing substraction with the current date. You as the property consumer don't need to know. So should we even be aware that properties are actually a pair of get_ and set_ functions under the hood? Take the following example:

class MyClass
{
   public int MyProperty
   {
      get { /* ... */ }
      set { /* ... */ }
   }

   public int MyField;

   public void MyMethod( ref int n )
   { /* Do something with n */ }

   public void MyTest()
   {
      MyMethod( ref MyField ); // Works fine
      MyMethod( ref MyProperty ); // Uh oh!
   }
}

If properties were really properly abstracted, you should be able to pass it as ref parameter to a method. But you can't. You will get a nice little compiler error saying "A property or indexer may not be passed as an out or ref parameter". Instead you'd have to implement MyTest like this:

public void MyTest()
{
   MyMethod( ref MyField ); // Still fine
   int temp = 0;
   MyMethod( ref temp );
   MyProperty = temp;
}

Wouldn't it be nice if the C# compiler would generate that extra boilerplate code in MSIL for you... thus keeping the abstraction... and never really revealing the fact that a property is really a pair of methods? Just a thought. Of couse if you know that a property is really two methods... you can take advantage of it if you want.
# Posted at 8:51 AM by Nick  |  Comment Feed Link No Comments  |  No Trackbacks

 Add to del.icio.us |  Digg this Post | Filed Under: Old Blog

Comments are closed.


© Copyright 2012 Nick Schweitzer
Powered By newtelligence dasBlog 1.9.7067.0
Theme Based on Design By maystar