what's wrong with assigning C# var types during definition?

dpopiz

Diamond Member
Jan 28, 2001
4,454
0
0
bool somevar;
somevar = 10;

is the same as

bool somevar = 10;


right? so why do some people still do it the former way (setting var type before defining the var)?
 

DJFuji

Diamond Member
Oct 18, 1999
3,643
1
76
preference, i guess. If i remember correctly, i started off assigning values while i assigned type during C++. But during VB6 I declared the variable first. Same with ASP 3.0/VBScript. Though i don't use types with VBScript. (i've never done a "dim variable = 50"...i'm not even sure it would work correctly). Now that i work with C#, i use both methods kinda interchangably.
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
There's no law either way.

My rule of thumb is to use declare-and-initialize when there is exactly one initialization statement

bool is_tuxbird = ( is_puffin || is_penguin ) ;

but not if there are multiple initializations

bool is_happy_bird;
if ( is_artctic )
is_happy_bird = ( is_puffin && is_smelt ) ;
else
is_happy_bird = ( is_penguin && is_cod ) ;

but this is just personal preference.
 

oog

Golden Member
Feb 14, 2002
1,721
0
0
it wasn't possible to do in vb6 without doing something like:

Dim objPerson as New Person

but this went through a different set of COM calls than to assign on a separate line, leading to unexpected behavior. maybe what you're seeing is a carry-over from that.

btw, i wouldn't want to assign 10 to a variable declared as bool.