From 19f32b02ff72f25b74ee77c16a3c26a253cfd708 Mon Sep 17 00:00:00 2001
From: NLHaarP <149793688+NLHaarP@users.noreply.github.com>
Date: Fri, 3 Nov 2023 13:28:34 +0100
Subject: [PATCH] Add support for Nullable Types

Trying to deserialize an object with nullable properties results in an InvalidCastException.

See also https://stackoverflow.com/questions/3531318/convert-changetype-fails-on-nullable-types
---
 CsvSerializerDotNet/Deserializer.cs | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/CsvSerializerDotNet/Deserializer.cs b/CsvSerializerDotNet/Deserializer.cs
index d87bb9b..de9cc4f 100644
--- a/CsvSerializerDotNet/Deserializer.cs
+++ b/CsvSerializerDotNet/Deserializer.cs
@@ -134,7 +134,10 @@ private int IndexOf(char[] array, char element, int startingIndex = 0)
                     if (property == null)
                         throw new CsvDeserializationExcepion("Public property '" + doc.Headers[i].Replace(" ", "") + "' not found in the given model");
                     else
-                        property.SetValue(obj, Convert.ChangeType(r.Values[i].ToString(), property.PropertyType));
+                    {
+                        Type propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
+                        property.SetValue(obj, Convert.ChangeType(r.Values[i].ToString(), propertyType));
+                    }
                 }
 
                 result.Add(obj);