{"id":2658,"date":"2019-10-11T09:58:57","date_gmt":"2019-10-11T08:58:57","guid":{"rendered":"https:\/\/solidt.eu\/site\/?p=2658"},"modified":"2022-07-25T08:33:25","modified_gmt":"2022-07-25T07:33:25","slug":"c-set-nullable-type-properties","status":"publish","type":"post","link":"https:\/\/solidt.eu\/site\/c-set-nullable-type-properties\/","title":{"rendered":"C# set nullable type properties"},"content":{"rendered":"\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">        private static bool IsNullableType(Type type)\n        {\n            return type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition().Equals(typeof(Nullable&lt;>));\n        }\n\n        private static void SetPropertyValueFromProperty(string location, object fromObject, PropertyInfo fromProperty, object toObject, PropertyInfo targetProperty)\n        {\n            if (fromProperty != null)\n            {\n                try\n                {\n                    var propertyValue = fromProperty.GetValue(fromObject, null);\n                    if (propertyValue != null)\n                    {\n                        \/\/ Cast type\n                        if (propertyValue.GetType() != targetProperty.PropertyType)\n                        {\n\n                            var t = propertyValue.GetType();\n                            var u = Nullable.GetUnderlyingType(t);\n                            var targetType = IsNullableType(targetProperty.PropertyType) ? Nullable.GetUnderlyingType(targetProperty.PropertyType) : targetProperty.PropertyType;\n\n                            if (propertyValue is IConvertible)\n                            {\n                                propertyValue = Convert.ChangeType(propertyValue, u ?? t);\n\n                                try\n                                {\n                                    if (targetType.IsEnum)\n                                    {\n                                        var enumTargetType = Enum.GetUnderlyingType(targetType);\n                                        propertyValue = TypeCast(propertyValue, enumTargetType);\n                                        \/\/propertyValue = Convert.ChangeType(propertyValue, enumTargetType);\n                                    }\n                                    else\n                                    {\n                                        propertyValue = Convert.ChangeType(propertyValue, targetType);\n                                    }\n                                }\n                                catch (Exception ex)\n                                {\n                                    \/\/ Ignore: Can not change type\n                                    LoggingHelper.Logger.Debug(ex.Message);\n                                }\n                            }\n\n                            if (propertyValue.GetType() != targetType)\n                            {\n                                try\n                                {\n                                    propertyValue = TypeCast(propertyValue, targetType);\n                                }\n                                catch (Exception ex)\n                                {\n                                    \/\/ Ignore: Can cast type\n                                    LoggingHelper.Logger.Debug(ex.Message);\n                                }\n                            }\n                        }\n                    }\n\n                    try\n                    {\n                        \/\/ Dit moet eigenlijk wel altijd goed gaan\n                        targetProperty.SetValue(toObject, propertyValue, null);\n                    }\n                    catch (Exception ex)\n                    {\n\n                        LoggingHelper.Logger.Warn(ex.Message);\n                        LoggingHelper.Logger.Warn($\"{location}: Problem when setting field while using reflection {targetProperty.Name}\");\n                    }\n                }\n                catch (Exception ex)\n                {\n                    \/\/ Hier kom je wanneer bepaalde velden niet meer bestaan\n                    LoggingHelper.Logger.Warn(ex.Message);\n                    LoggingHelper.Logger.Warn($\"{location}: Problem with field value while using reflection {targetProperty.Name}\");\n                }\n            }\n            else\n            {\n                LoggingHelper.Logger.Warn($\"{location}: Field not found while using reflection {targetProperty.Name}\");\n            }\n        }<\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static void SetValue(object inputObject, string propertyName, object propertyVal)\n{\n    \/\/find out the type\n    Type type = inputObject.GetType();\n \n    \/\/get the property information based on the type\n    System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName);\n \n    \/\/find the property type\n    Type propertyType = propertyInfo.PropertyType;\n     \n    \/\/Convert.ChangeType does not handle conversion to nullable types\n    \/\/if the property type is nullable, we need to get the underlying type of the property\n    var targetType = IsNullableType(propertyInfo.PropertyType) ? Nullable.GetUnderlyingType(propertyInfo.PropertyType) : propertyInfo.PropertyType;\n     \n    \/\/Returns an System.Object with the specified System.Type and whose value is\n    \/\/equivalent to the specified object.\n    propertyVal = Convert.ChangeType(propertyVal, targetType);\n \n    \/\/Set the value of the property\n    propertyInfo.SetValue(inputObject, propertyVal, null);\n \n}\nprivate static bool IsNullableType(Type type)\n{\n    return type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition().Equals(typeof(Nullable&lt;>));\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[6,4,1],"tags":[],"class_list":["post-2658","post","type-post","status-publish","format-standard","hentry","category-dotnet","category-programming","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2658","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/comments?post=2658"}],"version-history":[{"count":2,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2658\/revisions"}],"predecessor-version":[{"id":2662,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/2658\/revisions\/2662"}],"wp:attachment":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/media?parent=2658"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/categories?post=2658"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/tags?post=2658"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}