Tuesday, March 13, 2012

Should I declare my varaibles at the top of the method, or can i just declare them as I us

I am wondering about the standard on C# or VB.net

should I be declaring my method variables at the begining of the method or can I just declare them through out the code as I need it ?

is there any standard that is recomended or it does not matter t

thank you

my preference is to declare the variables at the top of the method all nice and neat and together.
variable instances are then created only as needed.

one exception to this is when i enumerate. i usually create the variable inline for the enumeration like this:

For Each objAs someObjectIn someObjectCollection'do something with the new var named: obj obj.blah obj.blahblahNext


Hi John,

I used to declare all of my variables at the top of the method and fields at the top of a class. Over time, I've gotten into the habit of declaring a variable just before I use it, which puts it closer to the code that is using it, which could help the code be more readable (my opinion or course). I don't know of any standard on this one topic. You could check out the.NET Framework Class Library Design Guidelines, which a lot of people refer to.

Joe


Standard practice is to declare all local variables at the beginning of the method. My view is to do what ever you find easiest, although if you have a boss or someone else to impress, you should be aware of the best practices.

0 comments:

Post a Comment