Link to home
Start Free TrialLog in
Avatar of scm0sml
scm0sml

asked on

which line of code is better c# 4

Just a quick question...

I'm wondering which if either of the following lines of code are better and if I should/shouldn't be doing one or the other....

Customer c;
c = db.Customers.FindById(Convert.ToInt32(hdnCustomerID.Value));

Open in new window


OR

Customer c = db.Customers.FindById(Convert.ToInt32(hdnCustomerID.Value));

Open in new window


Which is "industry standard"/correct way of doing it?
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of scm0sml
scm0sml

ASKER

kaufmed if I went with your example there, should I be declaring c as Customer c = null; or not?
It's a good indication to the reader coming behind you that you (yourself) understood that you weren't initializing the variable in its declaration, but you don't have to. The only time you must do that (AFAIK) is if you were referring to "c" outside of the body of the if. In that case, the compiler wouldn't know if you understood that the variable wasn't initialized, and it would give you an error stating uninitialized variable.

e.g.

Customer c = null;  // Must do to prevent compiler error on last line

try
{
    if (someExceptionGeneratingCondition)
    {
        c = db.Customers.FindById(Convert.ToInt32(hdnCustomerID.Value));
    }
}
catch (Exception ex)
{
    throw new ApplicaitonExcption("Exception-generating condition generated an exception", ex);
}

c.SomeMethod();

Open in new window

Hi scm0sml,

I know you have asked a specific question, but I could not resist.
how about we use int.tryParse and throw exception if it returns false?

Regards,
Chinmay.