public static BsonValue MapToBsonValue(
object value, // will be mapped to an instance of the BsonValue class for bsonType
BsonType bsonType
) {
if (value == null) {
throw new ArgumentNullException("value");
}
var valueType = value.GetType();
if (valueType.IsEnum) {
valueType = Enum.GetUnderlyingType(valueType);
switch (Type.GetTypeCode(valueType)) {
case TypeCode.Byte: value = (int) (byte) value; break;
case TypeCode.Int16: value = (int) (short) value; break;
case TypeCode.Int32: value = (int) value; break;
case TypeCode.Int64: value = (long) value; break;
case TypeCode.SByte: value = (int) (sbyte) value; break;
case TypeCode.UInt16: value = (int) (ushort) value; break;
case TypeCode.UInt32: value = (long) (uint) value; break;
case TypeCode.UInt64: value = (long) (ulong) value; break;
}
valueType = value.GetType();
}
Conversion conversion; // the conversion (if it exists) that will convert value to bsonType
if (fromToMappings.TryGetValue(Mapping.FromTo(valueType, bsonType), out conversion)) {
return Convert(value, conversion);
}
// these coercions can't be handled by the conversions table (because of the interfaces)
switch (bsonType) {
case BsonType.Array:
if (value is IEnumerable) {
return new BsonArray((IEnumerable) value);
}
break;
case BsonType.Document:
if (value is IDictionary) {
return new BsonDocument((IDictionary) value);
}
break;
}
string message = string.Format(".NET type {0} cannot be mapped to BsonType.{1}.", value.GetType().FullName, bsonType);
throw new ArgumentException(message, "value");
}