Adrian Hara

Working through the .NET maze

  Home  |   Contact  |   Syndication    |   Login
  42 Posts | 0 Stories | 83 Comments | 10 Trackbacks

News

Archives

Post Categories

Today I came across a nice feature of the ConfigurationElement framework class (for those of you who don't know what it's used for, you might want to check out this post). I needed to have a Point represented in the config file, like so: <someElement topLeft="100,100"/>. So in the code for my derived ConfigurationElement class I wrote some quick code to parse the string and return a Point, like so:

[ConfigurationProperty("graphTopLeft", IsRequired = false)]

public Point GraphTopLeft

{

      get { return ParsePoint(this["graphTopLeft"].ToString()); }

      set { this["graphTopLeft"] = value; }

}

 

 To my surprise, the string the ParsePoint method got called with looked something like "X=100 Y=100", instead of the "100,100" I was expecting. If you're thinking that the string above looks like a Point.ToString() result...well...you're right. Since the indexer of the ConfigurationElement class returns an object, I had to set a breakpoint in the code and look at the result of the indexer call and sure enough, a Point it was.

 

So how is that possible? Surely ConfigurationElement doesn't check and parse the string into a Point itself.

 

My first (dumb) thought was that maybe the Point struct had an implicit conversion operator from a string (did I mention that it was a dumb thought?). Then, as any good developer should, I fired up Reflector and examined the "code" of the ConfigurationElement class. After some digging I found the (somewhat obvious) reason: it uses a TypeConverter!

 

Specifically, the ConfigurationProperty class (which is a typed wrapper over a configuration attribute) has a ConvertFromString method, which basically just uses the TypeConverter of the type it represents (in my case, Point). Voila! Very nice and clean design, imho, which also means that you can use custom types in your config file, as long as they have an associated TypeConverter...

posted on Tuesday, October 31, 2006 5:38 PM