public static String ToBase64(this Object input, Base64FormattingOptions base64FormattingOptions = Base64FormattingOptions.None) { if (input == null) { return(String.Empty); } Type type = input.GetType(); // typeof(TObject); // Add support for Nullable types if (type.IsNullable()) { type = type.GetGenericArguments()[0]; } MethodInfo methodInfo; // Throw in a little static reflection caching if (!ParserUtilities._byteArrayMap.TryGetValue(type, out methodInfo)) { // Attempt to find inbuilt ToByteArray methods methodInfo = type.GetMethod("ToByteArray", new Type[] { }); // Null the mapping if the return type is wrong if ((methodInfo == null) || (methodInfo.ReturnType != typeof(Byte[]))) { ParserUtilities._byteArrayMap[type] = null; } else { ParserUtilities._byteArrayMap[type] = methodInfo; } } // Then use the inbuilt methods if (methodInfo != null) { return(Convert.ToBase64String((Byte[])methodInfo.Invoke(input, null), base64FormattingOptions)); } // Throw in a little static reflection caching if (!ParserUtilities._parserMap.TryGetValue(type, out methodInfo)) { // Attempt to find inbuilt parsing methods methodInfo = type.GetMethod("Parse", new Type[] { typeof(String) }); ParserUtilities._parserMap[type] = methodInfo; } // If there's inbuilt parsing methods, assume there is a useful ToString method if (methodInfo != null) { return(Convert.ToBase64String(Encoding.UTF8.GetBytes(input.ToString()), base64FormattingOptions)); } return(BinaryUtilities.ToBinary(input, base64FormattingOptions)); }