Browse Source

Allow null values for nullable types

Do a null check and allow null values for nullable types in the
DefaultTypeConverter
Brian Beard 11 years ago
parent
commit
43e2331baf
2 changed files with 37 additions and 2 deletions
  1. 20 0
      Jint.Tests/Runtime/InteropTests.cs
  2. 17 2
      Jint/Runtime/Interop/DefaultTypeConverter.cs

+ 20 - 0
Jint.Tests/Runtime/InteropTests.cs

@@ -52,6 +52,26 @@ namespace Jint.Tests.Runtime
             RunTest(@"
                 assert(square(10) === 100);
             ");
+        }
+
+        [Fact]
+        public void DelegateWithNullableParameterCanBePassedANull()
+        {
+            _engine.SetValue("isnull", new Func<double?, bool>(x => x == null));
+
+            RunTest(@"
+                assert(isnull(null) === true);
+            ");
+        }
+
+        [Fact]
+        public void DelegateWithObjectParameterCanBePassedANull()
+        {
+            _engine.SetValue("isnull", new Func<object, bool>(x => x == null));
+
+            RunTest(@"
+                assert(isnull(null) === true);
+            ");
         }
 
         [Fact]

+ 17 - 2
Jint/Runtime/Interop/DefaultTypeConverter.cs

@@ -16,7 +16,17 @@ namespace Jint.Runtime.Interop
         }
 
         public object Convert(object value, Type type, IFormatProvider formatProvider)
-        {
+        {
+            if (value == null)
+            {
+                if (TypeIsNullable(type))
+                {
+                    return null;
+                }
+
+                throw new NotSupportedException(string.Format("Unable to convert null to '{0}'", type.FullName));
+            }
+
             // don't try to convert if value is derived from type
             if (type.IsInstanceOfType(value))
             {
@@ -125,6 +135,11 @@ namespace Jint.Runtime.Interop
             }
 
             return System.Convert.ChangeType(value, type, formatProvider);
-        }
+        }
+
+        private static bool TypeIsNullable(Type type)
+        {
+            return !type.IsValueType || Nullable.GetUnderlyingType(type) != null;
+        }
     }
 }