3 Replies - 374 Views - Last Post: 07 April 2013 - 08:18 AM Rate Topic: -----

#1 Magn0733  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 57
  • Joined: 04-April 13

Declaring variables in the constuctor

Posted 06 April 2013 - 07:32 PM

Hey guys!

I've noticed how many programmers declare their variables in the constructo or in a Initializer method.
Why is this?

What is the pros of doing so, and not just declare it where you make your variable? :)
Is This A Good Question/Topic? 0
  • +

Replies To: Declaring variables in the constuctor

#2 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1012
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Declaring variables in the constuctor

Posted 06 April 2013 - 10:29 PM

You'll have to provide an example. Declaring variables in the constructor means they are only available in that method. I think you are referring to something else.

This post has been edited by Momerath: 06 April 2013 - 10:29 PM

Was This Post Helpful? 1
  • +
  • -

#3 Magn0733  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 57
  • Joined: 04-April 13

Re: Declaring variables in the constuctor

Posted 07 April 2013 - 08:09 AM

Ahh sure. :)

using System;

namespace DeclaringVariables
{
    public class VariableClass
    {
        int justANumber;  //Why not give it a value here?
        string justAString; //Same here?

        public VariableClass()
        {
            justANumber = 10;
            justAString = "HugoBob";
        }
    }
}



You see? :)
Why give the variables value in the constructer and not where you declare them? :)
Was This Post Helpful? 0
  • +
  • -

#4 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2153
  • View blog
  • Posts: 3,315
  • Joined: 21-June 11

Re: Declaring variables in the constuctor

Posted 07 April 2013 - 08:18 AM

Often the values with which the variables are initialized depend on the arguments given to the constructor. Classes also often have multiple constructors that initialize the variables to different values. In those cases you wouldn't be able to initialize the variables in their declaration.

In the code sample you posted, there is only a single constructor with no arguments. In that case it would be perfectly possible to initialize the variables in their declaration. So in that case it's just a matter of preference.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1