Godless667
Godless667

Reputation: 283

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?

Upvotes: 6

Views: 8546

Answers (4)

alanthinker
alanthinker

Reputation: 53

private static void TryToDecimal(string str, Action<decimal> action)
{
        if (decimal.TryParse(str, out decimal ret))
        {
            action(ret);
        }
        else
        {
            //do something you want
        }
}

TryToDecimal(strList[5], (x) => { st.LastTradePrice = x; });
TryToDecimal(strList[3], (x) => { st.LastClosedPrice = x; });
TryToDecimal(strList[6], (x) => { st.TopPrice = x; });
TryToDecimal(strList[7], (x) => { st.BottomPrice = x; });
TryToDecimal(strList[10], (x) => { st.PriceChange = x; });

Upvotes: 0

yfeldblum
yfeldblum

Reputation: 65435

Write an extension method.

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

Upvotes: 11

Ali Ers&#246;z
Ali Ers&#246;z

Reputation: 16086

I suggest separate the TryParse part from 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);
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500015

I'd use an alternative implementation TryParse which returns an 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 - either way it'll be visible in your code.)

Upvotes: 3

Related Questions