Calvin Froedge Calvin Froedge - 4 years ago 112
C# Question

Extending System.Convert

System.Convert has a really useful utility for converting datatypes from one type to another. In my project, I have many custom types. I want to convert command line arguments to these custom types (some of which are quite complex). It would be nice if these existed within System.Convert so I could just do something like this:

Convert.ToMyCustomType(args[1])


I'd like for this to show up in the Visual C# IDE as I type. I know that I could simply create a routine to convert types but I would like the type conversions to be handled in the same manner as what's already built into the framework. Has anyone had success doing this in the past?

Answer Source

No, you can't add them to the Convert class - I would suggest adding conversion methods to your actual types, such as:

MyCustomType.FromInt32(...)

and instance methods going the other way:

int x = myCustomType.ToInt32();

(Static factory methods are often better than adding lots of overloaded constructors, IMO. They allows various alternatives - including returning a null value where appropriate, or caching - and can make the calling code clearer.)

I would also strongly recommend that you don't go overboard on the number of conversions you supply. Not many custom types really have a single natural conversion from all kinds of primitive types.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download