How to set Nullable Types via Reflection on Properties in C# / .NET

Here is a Code-Snippet from a generic CSV -> Object Importer/Mapper I wrote. At some point I ran into an issue with Nullable types / values which I had to set (and convert) based on strings from the CSV file.

  1. public virtual void HandlePropertyAssignment(PropertyInfo pi,
  2. string propertyValue,
  3. T instance)
  4. {
  5. try
  6. {
  7. if (
  8. pi.PropertyType.GetGenericArguments() != null &&
  9. pi.PropertyType.GetGenericArguments().Length > 0 &&
  10. pi.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))
  11. )
  12. {
  13. Type genericType = pi.PropertyType.GetGenericArguments()[0];
  14. pi.SetValue(instance, Convert.ChangeType(propertyValue, genericType), null);
  15. }
  16. else
  17. {
  18. pi.SetValue(instance, Convert.ChangeType(propertyValue, pi.PropertyType), null);
  19. }
  20. }
  21. catch (System.Exception ex)
  22. {
  23. throw new DAOException(String.Fromat("Could not convert {0} to property {1} of type {2}",
  24. propertyValue,pi.Name,pi.PropertyType),ex);
  25. }
  26. }
Note: T is a Generic Type.

Comments

Thx man.

Thx man.

Thanks man! Very useful tip!

Thanks man!

Very useful tip!

Great post, thanks!

Great post, thanks!

Thankyou! Thankyou! Thankyou!

This was driving me crazy and I did not find documentation anywhere else.

Thanks for that snippet :)

Yesterday I was searching all the time for setting nullable types via reflection. Today, first hit was your blog and now the secret is  raised :)

greets
paddy