Ta01
Ta01

Reputation: 31610

Generic Replacement for a couple of Funcs

I'm parsing extensive xml content and populating a DTO for submission to partner end point. The xml content is stored in text files which I read periodically and send on. Anyhow, I now find myself with Funcs like this:

Func<string, int> ConvertInt= (p) => String.IsNullOrEmpty(p) ? 0 : Convert.ToInt32(p);

I check if the element I'm reading doesn't contain a value, and if it doesn't send the default, i.e. in an integers case, a 0. I have similar ones for double, and DateTime?, is there anyway to convert this so I could have say an extension method that would handle all types, i.e. ints, doubles, and DateTimes? Again, the reason I'm doing this conversion is because lets say for some integer value that that DTO expects, but is not required, I don't want to try to cast an empty string to an it and so on...if there is no Date value I just want to return a null because the DTO accepts nullable datetimes hence I wrote the funcs, and am looking to consolidate.

Upvotes: 3

Views: 87

Answers (1)

mathieu
mathieu

Reputation: 31202

You should have a look at the TypeConverter class : http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx

protected X Convert<X>(string value)
{
    X val = default(X);

    var tc = TypeDescriptor.GetConverter(typeof(X));

    if (!string.IsNullOrEmpty(value) && tc.CanConvertFrom(typeof(string)))
    {
        val = (X)tc.ConvertFromString(value);
    }

    return val;
}

Upvotes: 8

Related Questions