Here is an extension method for string that makes it easy - almost trivial - to convert the value held by the string
into another type.
How does this work?
Check for the special case of conversion to a string, and just return the same value if required.
Use a TypeConverter
to convert if one is available that can handle a string. This handles a bunch of simple types like int,
bool, DateTime, TimeSpan, Color and most enum types.
If the target type has a constructor that takes a single string, create an instance by passing the value to that
constructor. This handles some more complex classes like Version and provides another way for your own types to hook
into the conversion process.
Because this method uses reflection, performance is relatively poor - you may not want to use it in its current form
in the midst of a tight loop. Like all performance issues however, measure performance with a profiler before you make
changes.
Comments
blog comments powered by Disqus