should I always declare my variables before assigning

I've always been in the habit of declaring my variables at the top of the page as null and then assigning them, normally inside my try{} or main block of code, something along the lines of the below:
protected void Page_Load(object sender, EventArgs e)
    {
        List<Job> jobs = null;

        if (!Page.IsPostBack)
        {
            jobs = new List<Job>;

            //and so on....
        }
    }

Open in new window


Is that good/bad practice or would I be better off just creating a new list inside my main if.

Is it the case I should only do this if I need the list in scope for my finally block or some code outside of the main if....?
scm0smlAsked:
Who is Participating?
 
Neil RussellConnect With a Mentor Technical Development LeadCommented:
Yes. Good practice is ALWAYS to pre declare ALL variables before use.
0
 
IanThConnect With a Mentor Commented:
its always safer to declare the variable before you use it imho
0
 
scm0smlAuthor Commented:
so you are saying as I'm doing it in your opinion is correct?
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
Lalit ChandraConnect With a Mentor Commented:
Every declared variable has it scope. the variable that you define outside oof methods, it become global to the class,means its get  of memory every time the class is initiated. and as it is global, there is no any control of their access,and hence any wrong access (updation) is done  by some other method while it being used by any other method.

So,By Standards, its a good habit to limit a variable to a limited scope (method scope) until an unless there is a serious need of declaring Global variables.
0
 
scm0smlAuthor Commented:
It's what I've always done but have never been clear whether it was correct or not.

Is there any reason for this as such?
0
 
scm0smlAuthor Commented:
Lalit-Chandra I understand scope, I was referring to inside my methods more so....
0
 
Lalit ChandraCommented:
ok,then you r doing it in a right way.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.