NoWar
NoWar

Reputation: 37633

byte.TryParse() which approach is better

I just need to advice to make sure which approach is better

1)

byte flag = 2; 
byte.TryParse(strFlag, out flag);

2)

byte flag; 
if (!byte.TryParse(strFlag, out flag)) 
{ 
    flag = 2; 
}

Thanks!!!

Upvotes: 1

Views: 2767

Answers (5)

Royi Namir
Royi Namir

Reputation: 148524

2 different things

in the latter you have a zone of : "what will i do if it will fail"

in the former you don't have it. - it will override the value with default value.

Upvotes: 0

Guvante
Guvante

Reputation: 19203

TryParse will do the following in your example:

  • If strFlag is a valid byte, decode it and set flag to it. Return true.
  • Otherwise set flag to 0 and return false.

Note that this means that flag will always be set by TryParse.

If you want flag to be 2 in the default case you will need to use the later syntax.

Upvotes: 1

Destrictor
Destrictor

Reputation: 752

Obviously it'd be approach #2.

The reason is that #1 will overwrite the value of your variable with the default value of the type (in this case 0)

Upvotes: 1

Edward
Edward

Reputation: 3276

The second.

Once you pass an out parameter to a method, the method can do anything it wants to it.

Upvotes: 0

Thomas Calc
Thomas Calc

Reputation: 3014

I assume you want to set flag to 2 if TryParse fails.

The first approach is wrong. If it fails, it will overwrite your value with 0 (as that is the default value of the byte type). You should use the second solution.

Upvotes: 7

Related Questions