Das
Das

Reputation: 59

Null validation for getting property values using reflection

Here i am trying to add a generic list of values to a dictionary.

Below is the DocDetails class

public class DocDetails
{
   public string DocId { get; set; }
   public string Description { get; set; }
   public string Category { get; set; }
}

Iam getting a list of DocDetails in docDetailsList object. Using this am getting each item of DocDetails and getting the property name and value and then adding to a Dictionary.

Dictionary<string, List<object>> docDict = new Dictionary<string, List<object>>();

  foreach (var doc in docDetailsList)
     {
          var dict = doc.GetType().GetProperties().ToDictionary(
            m => m.Name, m => new List<object>()
             {
                m.GetValue(doc, null).ToString()
             });
         docDict.Add(dict);
      }

When trying to get property value in this line m.GetValue(doc, null).ToString() getting exception if the value is null. How can i validate that , even if its null i need to add that property name to the list with an empty value. Can any one help me out here please

Upvotes: 1

Views: 178

Answers (1)

Poul Bak
Poul Bak

Reputation: 10929

Instead of:

m.GetValue(doc, null).ToString()

You can check, if it's null before calling ToString():

m.GetValue(doc, null) != null ? m.GetValue(doc, null).ToString() : null

Upvotes: 1

Related Questions