Skip to main content
1 of 3
Rossco
  • 448
  • 4
  • 13

This would perhaps have been better as a comment to the previous answer but I don't have enough rep yet.

The dictionary and lambdas may be adding overhead to the method so here is an alternative that might start you down the right track.

    static string ValueToString(object value)
    {
        if (value == null)
            return "";

        Type valueType = value.GetType();

        if (valueType == typeof(string))
        {
            return value as string;
        }
        if (valueType == typeof(decimal))
        {
            return ((decimal)value).ToString(
                "0.############################",
                CultureInfo.InvariantCulture);
        }
        if (valueType == typeof(DateTime))
        {
            return ((DateTime)value).Ticks.ToString("X");
        }
        if (typeof(Enum).IsAssignableFrom(valueType))
        {
            return ((int)value).ToString("X");
        }
        
        return Convert.ToString(value,
            CultureInfo.InvariantCulture);
    }

One thing that would be interesting to know is whether is the type testing that is slow or the conversion once you know what type you have. My approach has focussed on the testing rather than the conversion. If the latter turned out to be the slow part then you will not get much benefit from this code.

This answer might give you some insight into the issue with the enum conversion. It rightly points out that you can't convert a variable typed as Enum to int using a direct cast.

Rossco
  • 448
  • 4
  • 13