How To Remove Null Properties From Anonymous Object C#

Introduction

 
We are going to see about the anonymous type, how to create them, how to remove the properties which have the nullable value.
 

Anonymous Type

  1. An Anonymous type is a new feature in C# 3.0 which is used to create a new anonymous type.
  2. It is used for temporary purposes within the class and it can contain only the public read-only properties.
  3. An Anonymous type gives a suitable way to protect the state of the type and behavior.
  4. Anonymous types are lightweight and the class contains only the properties.
  5. An Anonymous type is very much connected to the Delegates. It is a kind of improvisation from the Delegates.
  6. Anonymous type is mainly used for performance.

How to create an Anonymous type

 
We can create anonymous types by using the new keyword together with an object initializer.
 
The below example gives an anonymous type that is initialized with four properties named FirstName, LastName, MiddleName, and MailingAddress. The compiler will implicitly assign the types to the properties based on the types of their values. 
  1. var anonymousObj = new    
  2. {    
  3.         FirstName = "Jhon",    
  4.         LastName = "Peter",    
  5.         MiddleName = "L",    
  6.         MailingAddress = null    
  7. };    
How to remove the null properties from the anonymous object.
 
From the above anonymous object, the "MailingAddress" value is set as null.
 
If we want to remove all the null values from the anonymous object, then I will show you how to remove null values from anonymous object variable. we can easily delete null values from json object using Json Convert with Null value handlings.
 
Remove null properties
 
Below, I give you sample code to remove all null values in an anonymous object (anonymous object).
  1. var serilaizeJson= JsonConvert.SerializeObject(anonymousObj, Formatting.None,        
  2. new JsonSerializerSettings        
  3. {        
  4. NullValueHandling = NullValueHandling.Ignore        
  5. });        
  6.       
  7. var result = JsonConvert.DeserializeObject<dynamic>(serilaizeJson);      
  8.     
  9. //Output    
  10.     
  11. {    
  12.  FirstName = "Jhon",      
  13.  LastName = "Peter",      
  14.  MiddleName = "L"    
  15. }    
By using the jsonConvert.SerializeObject and ignoring the NullValueHandling. We can ensure that properties containing the null value are completely removed from the anonymous object.