Thursday, October 06, 2005

Byte Array Indexers and Properties

I ran into a neat problem this afternoon while trying to use a byte array indexer to set an array cell to a particular value via a business entity property.  I say it was a “neat problem” because things didn’t work like I’d expected, but I was able to quickly figure out what the issue was.  It would have been a “#@%">“#@%*&!!! problem” if the lightbulb wouldn’t have turned on quickly.

My biz entity has a byte array for storing photos, with a few checks on the setter to ensure we’re not trying to store too large an image:

private byte[] _photo = null;
public byte[] Photo        
{            
   get { return _photo; }            
   set            
   {                
      if (value != null)                
      {                    
         if (value.Length > NS_MAX_IMAGE_SIZE)                    
         {                        
            throw new ArgumentOutOfRangeException("value", value, "Image size too large");                    
          }                
      }                //Clone array, not assign since Arrays are reference types                
      _photo = (byte[])value.Clone();                
      _isModified = true;            
    }       
}

The “neat problem” popped up as I was writing a test to check the Equals() method when one of the two entities being compared had its Photo property as null.  I create one BE with Photo as null, then set the other to a non-null by storing in a single byte:

right.Photo[0] = 0xF;

Well, that got me a NullException error, so I stepped through trying to figure out why the null checks in the property’s setter weren’t behaving as I expected.  Stepping into the assignment above ( right.Photo[0] = 0xF; ) jumped me into the Property’s getter, not the setter.

‘Tis a puzzlement, to quote King Mongkut.

Wait.  Slap forehead.  I’m using an indexer to set a cell of the byte array.  That means the statement needs to work on the actual byte array, so of course the getter is used to return the array before the value’s set.  Duh.

Now I’m creating a new byte array with the appropriate value and using the property’s setter.  Works much better and it was a “neat” problem to work through.  (Quickly, thankfully!)

Now Playing: Guster — Lost and Gone Forever.  Maybe even better than Keep it Together, an album which I love.

No comments:

Subscribe (RSS)

The Leadership Journey