Sometimes 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‘. A solution would be to change the code as follows:

if ( internalName == FieldsList.Title.ToString() )

But that’s pretty ugly. Implicit type conversion to the rescue.

What we want is for the Field type to be able to behave as a string. Adding the following code to the Field class will do just that:

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 to string, use the InternalName property”. Now your code will compile.

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.

If you liked this post, please click on one of the advertisements below. Thanks!

0 Responses to “Converting an Object to/from Anything – Implicit Type Conversion”

  1. No Comments

Leave a Reply