2

I copy this code form StackOverlow question here, but I got feedback that it is not working on computers with specific datetime format. Do you have some idea how to fix it elegantly?

The problem is that the formating method is generic and object.ToString does not have overload with CultureInfo parameter.

private string UrlEncodeObject(object o)
{
    var properties = from p in o.GetType().GetProperties()
        where p.GetValue(o, null) != null
        select p.Name + "=" + System.Net.WebUtility.UrlEncode(p.GetValue(o, null).ToString());

    string queryString = String.Join("&", properties.ToArray());
    return queryString;
}

I expect that there might be similar problems with specific decimal symbol etc.

Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
  • Can you check the type of `p` and, if it's a `DateTime` (or `DateTime?` possibly) then cast it as such to use the overload of `.ToString()` on that property? – David Dec 21 '18 at 15:26
  • Why not passing generic type to the function and casting object to it? – Mohammed Noureldin Dec 21 '18 at 15:26

1 Answers1

3

That code is already doing a lot of things, don't you want to decompose that method into smaller ones?

You could extract a method to get the string value:

select p.Name + "=" + GetPropertyValue(o, p);

And implement it like this:

private string GetPropertyValue(PropertyInfo i, object o)
{
    var propertyValue = p.GetValue(o, null);

    string stringValue;

    if (propertyValue.GetType() == typeof(DateTime))
    {
        stringValue = ((DateTime)propertyValue).ToString(SomeCultureInfo);
    }
    else
    {
        stringValue = propertyValue.ToString();
    }

    return System.Net.WebUtility.UrlEncode(stringValue);
}

And of course implement various null checks and other improvements, but you get the general idea. Also, what if a property in turn is of a complex type?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272