Showing posts with label Generic Conversion. Show all posts
Showing posts with label Generic Conversion. Show all posts

Tuesday, June 9, 2009

Generic Type Conversion

While working on the Virtual Earth map application, I discovered the need to parse data from a string of characters. So I searched the net and found this answer on stack overflow: generic-type-conversion-from-string . I like this code example because it looks like the simplest and most general approach:

public class TypedProperty<T> : Property
{
public T TypedValue
{
get { return (T)Convert.ChangeType(base.Value, typeof(T)); }
set { base.Value = value.ToString();}
}
}
But if you cut and paste the code into a Silverlight 2 or Silverlight 3 application it does not run. This is because the two argument version of the ChangeType method is not part of the Silverlight runtime. I guess I could have used the three argument version, but instead I implemented a function the uses reflection:


public bool TryParse<T>(string sValue, out T oValue) where T : IConvertible
{
oValue = default(T);

try
{
string[] parts = sValue.Split(':');
MethodInfo oMethod = typeof(T).GetMethod("Parse", new Type[] { typeof(string) } );
oValue = (T)oMethod.Invoke(null, new object[] { parts[1].Trim() });
return true;
}
catch { }
return false;
}
Silverlight Size vs. Functionality

You find this all the time in Silverlight development -- some of the tools, functions and features you have come to rely on in .NET are just not part of the lightweight Silverlight runtime. I read on one blog that programming with Silverlight is like going camping with .NET. In fact, I first learned this the hard way trying to recompile some previous .NET code. I couldn't include the existing library -- it had to be rebuilt using the Silverlight libraries. When I attempted to recompile it, I found that it needed to be reengineered to use functionality available in the Silverlight runtime.

I have always been able to find a creative solution to simple programming issues like the one above, and I think the ability to deliver my solution over the web to any machine, without creating a custom install, makes it worth the effort to find these alternative approaches.