Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using TryParse for Setting Object Property Values

I'm currently refactoring code to replace Convert.To's to TryParse.

I've come across the following bit of code which is creating and assigning a property to an object.

List<Person> list = new List<Person>();

foreach (DataRow row in dt.Rows)
{
     var p = new Person{ RecordID = Convert.ToInt32(row["ContactID"]) };

     list.Add(p);
}

What I've come up with as a replacement is:

var p = new Person { RecordID = Int32.TryParse(row["ContactID"].ToString(), out RecordID) ? RecordID : RecordID };

Any thoughts, opinions, alternatives to what I've done?

like image 758
Godless667 Avatar asked Dec 22 '22 14:12

Godless667


1 Answers

Write an extension method.

public static Int32? ParseInt32(this string str) {
    Int32 k;
    if(Int32.TryParse(str, out k))
        return k;
    return null;
}
like image 135
yfeldblum Avatar answered Jan 05 '23 23:01

yfeldblum