Click here to Skip to main content
Licence CPOL
First Posted 25 Feb 2010
Views 14,503
Bookmarked 25 times

Using LINQ for type conversion

By | 25 Feb 2010 | Article
Converting between types in .NET.

Introduction

.NET provides several ways to change the type of a value to another type at run-time. Each technique has its limitations. This article provides (yet) another alternative that works in all instances when the CLR is capable of performing a type cast.

Background

Two popular solutions to the problem of type conversion are to use System.Convert.ChangeType, or to obtain System.ComponentModel.TypeConverter and call its ConvertFrom method. The first method breaks when you try converting a value type T to System.Nullable<T>; the second one breaks when you try converting different numeric types, for example, float to double. These limitations appear especially frustrating, because the CLR has built-in capabilities to perform both types of conversion.

One way of using these type casting capabilities is to build a LINQ lambda expression, compile it into a Func<object,object>, and then use the compiled delegate every time we need to convert between two types.

Using the code

The code below implements this approach, wrapping it into an extension method of System.Type.

public static class TypeCast {
    // This is the method exposing the rest of the functionality
    public static object Cast(this Type type, object obj) {
        return GetConverter(type, obj)(obj);
    }
    private static readonly IDictionary<PairOfTypes,Func<object,object>> converters =
        new Dictionary<PairOfTypes,Func<object,object>>();
    private static readonly ParameterExpression convParameter =
        Expression.Parameter(typeof(object), "val");
    // This is the method with the "guts" of the implementation
    [MethodImpl(MethodImplOptions.Synchronized)]
    private static Func<object,object> GetConverter(Type targetType, object val) {
        var fromType = val != null ? val.GetType() : typeof(object);
        var key = new PairOfTypes(fromType, targetType);
        Func<object,object> res;
        if (converters.TryGetValue(key, out res)) {
            return res;
        }
        res = (Func<object,object>)Expression.Lambda(
            Expression.Convert(
                Expression.Convert(
                    Expression.Convert(
                        convParameter
                    ,   fromType
                    )
                ,   targetType
                )
            ,   typeof(object)
            )
        ,   convParameter
        ).Compile();
        converters.Add(key, res);
        return res;
    }
    // This class provides Equals and GetHashCode
    // for a pair of System.Type objects.
    private class PairOfTypes {
        private readonly Type first;
        private readonly Type second;
        public PairOfTypes(Type first, Type second) {
            this.first = first;
            this.second = second;
        }
        public override int GetHashCode() {
            return 31*first.GetHashCode() + second.GetHashCode();
        }
        public override bool Equals(object obj) {
            if (obj == this) {
                return true;
            }
            var other = obj as PairOfTypes;
            if (other == null) {
                return false;
            }
            return first.Equals(other.first)
                && second.Equals(other.second);
        }
    }
}

Now, you can use the Cast method like this:

double? x = typeof(double?).Cast(1.0);
int y = typeof(int).Cast(1.2345);

Happy coding!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

dasblinkenlight



United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralI cant get a simple example to build Pinmembertheperm5:55 9 Feb '11  
GeneralRe: I cant get a simple example to build Pinmemberdasblinkenlight6:28 9 Feb '11  
Generalgood one - have 5 from me PinmemberPranay Rana0:30 19 Dec '10  
GeneralInteresting thing... PinmemberPaulo Zemek6:17 26 Feb '10  
GeneralRe: Interesting thing... Pinmemberdasblinkenlight11:23 26 Feb '10  
QuestionWhat am I missing? PinmvpJosh Fischer8:59 25 Feb '10  
AnswerRe: What am I missing? Pinmemberdasblinkenlight9:31 25 Feb '10  
GeneralRe: What am I missing? PinmvpJosh Fischer14:05 25 Feb '10  
AnswerRe: What am I missing? Pinmemberdasblinkenlight18:30 25 Feb '10  
GeneralRe: What am I missing? PinmvpJosh Fischer4:18 26 Feb '10  
GeneralGetHashCode and the secrets of multiplying by 31 PinmemberMarc Brooks13:51 1 Mar '10  
GeneralRe: What am I missing? PinmvpPIEBALDconsult3:23 26 Feb '10  
AnswerRe: What am I missing? Pinmemberdasblinkenlight5:47 26 Feb '10  
GeneralInteresting, but... PinmemberPaulo Zemek8:57 25 Feb '10  
GeneralRe: Interesting, but... Pinmemberdasblinkenlight9:45 25 Feb '10  
GeneralRe: Interesting, but... [modified] PinmemberPaulo Zemek10:34 25 Feb '10  
GeneralRe: Interesting, but... Pinmemberdasblinkenlight18:01 25 Feb '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 25 Feb 2010
Article Copyright 2010 by dasblinkenlight
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid