Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Nulls to Empty String in an object

Tags:

c#

What is the easiest way to take an objects and convert any of its values from null to string.empty ?

I was thinking about a routine that I can pass in any object, but I am not sure how to loop through all the values.

like image 449
John Avatar asked Apr 06 '10 14:04

John


People also ask

Can we convert null to string?

If we concatenate null with an empty string (""), the result will be of string type. We can use this technique to convert null to string. We use + operator to concatenate the null and empty string("").

Can null convert to string in Java?

Both methods String. valueOf(Object) and Objects. toString(Object) essentially do the same thing: call the toString() method on a passed-in object. This is the case as long as it's not null or it doesn't return the string "null" when null is passed to them.

Is null and empty string the same in Java?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.

Can we assign null to string in C#?

In C#, there exist two types of variables which are value types and reference types. Value type variables cannot be assigned null, whereas we can assign null to reference type variables. As the string is a reference type, it can be null.


2 Answers

When your object exposes it's values via properties you can write something like:

string Value { get { return m_Value ?? string.Empty; } }

Another solution is to use reflection. This code will check properties of type string:

var myObject = new MyObject();
foreach( var propertyInfo in myObject.GetType().GetProperties() )
{
    if(propertyInfo.PropertyType == typeof(string))
    {
        if( propertyInfo.GetValue( myObject, null ) == null )
        {
            propertyInfo.SetValue( myObject, string.Empty, null );
        }
    }
}
like image 64
tanascius Avatar answered Oct 13 '22 06:10

tanascius


Using reflection, you could something similar to :

public static class Extensions
{
    public static void Awesome<T>(this T myObject) where T : class
    {
        PropertyInfo[] properties = typeof(T).GetProperties();
        foreach(var info in properties)
        {
            // if a string and null, set to String.Empty
            if(info.PropertyType == typeof(string) && 
               info.GetValue(myObject, null) == null)
            {
                info.SetValue(myObject, String.Empty, null);
            }
        }
    }
}
like image 35
Dynami Le Savard Avatar answered Oct 13 '22 05:10

Dynami Le Savard