Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 896
Calvin Froedge Avatar asked Apr 17 '12 18:04

Calvin Froedge


People also ask

How does convert ChangeType work?

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.

What are extension methods in C#?

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.

What is type of conversion in asp net?

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 in MVC?

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.


1 Answers

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.

like image 109
Jon Skeet Avatar answered Oct 23 '22 23:10

Jon Skeet