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?
ChangeType(Object, TypeCode) is a general-purpose conversion method that converts the object specified by value to a predefined type specified by typeCode . The value parameter can be an object of any type.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
Type conversion creates a value in a new type that is equivalent to the value of an old type, but does not necessarily preserve the identity (or exact value) of the original object. . NET automatically supports the following conversions: Conversion from a derived class to a base class.
What is extension method? Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With