Using TryParse to set object property values

I am currently reorganizing the code to replace Convert.To with TryParse.

I met the following bit of code that creates and assigns 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 came up with for replacement:

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

Any thoughts, opinions, alternatives to what I did?

+3
source share
3 answers

Write an extension method.

public static Int32? ParseInt32(this string str) {
    Int32 k;
    if(Int32.TryParse(str, out k))
        return k;
    return null;
}
+6
source

I would use an alternative implementation TryParsethat returns int?:

public static int? TryParseInt32(string x)
{
    int value;
    return int.TryParse(x, out value) ? value : (int?) null;
}

Then you can write:

var p = new Person { RecordID = Helpers.TryParseInt32(row["ContactID"].ToString()) ?? 0 };

(Or use a different default value if you want - it will be visible in your code anyway.)

+1
source

I suggest separating the TryParse part from the initializer. It will be more readable.

int recordId;
Int32.TryParse(row["ContactID"].ToString(), out recordID)

foreach (DataRow row in dt.Rows)
{
     var p = new Person{ RecordID = recordId };
     list.Add(p);
}
0
source

Source: https://habr.com/ru/post/1699458/


All Articles