Daniel Harvey
Daniel Harvey

Reputation: 379

PropertyInfo.GetValue(obj, null) truncating strings

This generic helper function iterates over a list of objects, accessing their public properties, and spitting out one comma delimited string per object.

    /// <summary>
    /// Format the properties as a list of comma delimited values, one object row per. 
    /// </summary>
    /// <typeparam name="T">Type of class contained in the List</typeparam>
    /// <param name="list">A list of objects</param>
    /// <returns>a list of strings in csv format</returns>
    public static List<string> ToCSV<T>(this IEnumerable<T> list)
        where T : class
    {
        var results = new List<string>();
        bool firstTime = true;
        foreach (var obj in list)
        {
            // header data
            if (firstTime)
            {
                firstTime = false;
                string line = String.Empty;
                foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
                {
                    if (propertyInfo.CanRead)
                    {
                        line += propertyInfo.Name + ',';
                    }
                }
                results.Add(line);
            }
            else
            {
                string line = String.Empty;
                foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
                {
                    if (propertyInfo.CanRead)
                    {
                        object value = propertyInfo.GetValue(obj, null);
                        if (value.GetType() == typeof(string))
                        {
                            line += "\"" + value.ToString() + "\"" + ",";
                        }
                        else
                        {
                            line += value.ToString() + ",";
                        }
                    }
                }
                results.Add(line);
            }
        }
        return results;
    }

One of the classes being iterated by this method has a string property, which is being truncated:

string BusinessItem { get; set; } // "0000", a legitimate business value

The problematic bit is here:

object value = propertyInfo.GetValue(obj, null); // value == 0

How do I get the value of the property as a string, not an int?

Upvotes: 0

Views: 1483

Answers (1)

Guffa
Guffa

Reputation: 700472

Consider this check:

if (value.GetType() == typeof(string) && (value as string).Contains(','))

It means that a string value will be written within quotation marks only if it contains a comma.

A string value of "0000" would be written as 0000, to the line. If the code that reads the file checks if a value is all digits to determine if it's a number, that would be parsed as a number, not read as a string. In that case you should write all strings withing quotation marks, not only strings that contains a comma.

Upvotes: 3

Related Questions