Converting an Object to/from Anything – Implicit Type Conversion
0 Comments Published by Erik Burger October 7th, 2008 in ProgrammingSometimes you discover a little gem that you just know you will be using over and over again. My latest discovery is implicit type conversion. Implicit type conversion basically allows you to convert any object to any other type. Note that not all conversions make sense.
As an example, let’s assume the following Field and FieldList classes:
public class Field<T> { public string InternalName { get; set; } public string DisplayName { get; set; } public T Value { get; set; } public Field(string name, string displayName, T value) { this.InternalName = name; this.DisplayName = displayName; this.Value= value; } } public abstract class FieldList { public static readonly Field<string> Title = new Field<string>( "Title", "Title", "An Example" ); // ... and so on }
Somewhere in your application, you are basing the flow of your logic on whether the internal name of a field matched the Title field:
string internalName = "Title"; if ( internalName == FieldsList.Title ) { // ... }
However, this will not compile with the error: Operator ‘==’ cannot be applied to operands of type ‘string’ and ‘ExampleApp.Field
if ( internalName == FieldsList.Title.ToString() )
But that’s pretty ugly. Implicit type conversion to the rescue.
What we want is for the Field
public static implicit operator string( Field<T> f ) { return f.InternalName; }
What this tells the compiler is that “if there is a need to convert the type Field
The following code will also work:
Field<string> f = new Field<string>( "Title", "Title", "An Example" ); Console.WriteLine( f );
Something interesting happens when we use formatting strings. Let’s execute the following code:
Field<string> f = new Field<string>( "Title", "Title", "An Example" ); Console.WriteLine( "The title is: {0}", f );
This will not print ‘Title’ as you would expect. Instead, it outputs ‘ExampleApp.Field`1[System.String]‘. So in this case, we’ll need to override the ToString() method:
public override string ToString() { return this; // Invokes implicit type conversion }
Now everything works exactly as we’d expect it to.


0 Responses to “Converting an Object to/from Anything – Implicit Type Conversion”
Please Wait
Leave a Reply