tags:

views:

41

answers:

1

I like .Net intrinsic data types' Parse and TryParse methods. I would like to define an interface to do similar thing like:

 public interface IParsable<T>
 {
    T Parse<TData>(TData input);
    bool TryParse<TData>(TData input, out T output);
 }

I tried to search from .Net and I cannot find this interface or similar one available. I try to follow the same practice as in .Net's APIs.

Basically, this interface just provides methods or APIs to convert an input to an output. It could be named as IMapTo. Not sure if there are something already available in .Net or public open source libraries? Any suggestions?

+2  A: 

In the case of string, I think you are best off with TypeConverter;

TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
T value = (T) converter.ConvertFromString(s);
string newS = converter.ConvertToString(value);

Sorry; I meant to add more but got disconnected (mobile data). The advantage of TypeConverter over (say) Convert.ChangeType is that you can add your own types to TypeDescriptor, either at compile time or runtime.

You are absolutely right that there is no Try... - and the IsValid method is very broken generally as far as I can tell - you can of course use an exception.

Marc Gravell
that's nice .net framework, at least I did not know. This makes me rethink my strategy. One thing is missing here is no TryParse like method available.
David.Chu.ca
I found something from msdn's article http://msdn.microsoft.com/en-us/library/ayybcxe5.aspx about TypeConverter. There are APIs for CanConvertTo and CanConvertFrom. Interesting to read it.
David.Chu.ca
@David - `CanConvert*` are only type-specific, so will only tell you whether `string` is valid - not whether `"123a456"` is valid.
Marc Gravell