6 Replies - 1240 Views - Last Post: 16 July 2010 - 10:35 AM Rate Topic: -----

#1 lookitstom  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 28
  • Joined: 12-July 10

can't seem to understand constructors and initializers

Posted 16 July 2010 - 08:45 AM

hey guys.
im reading my learning c# 3.0 book, and i've come up to this topic which absolutely looks like chinese to me... i cant understand nor the point, how its done or why...

first off the, constructors... what does it mean? why are they used? i just cant get this.... read the chapter like 4 times and i cant seem to get the hang of it.
according to the book - "to create a constructor, you create a method with te same name as the class that initializes the internal variables".

this is the code that appears in the book-
namespace Example_7_3__Constructor
{
public class Box
{
// private variables
private int length;
private int width;
private int height;

// public methods
public void DisplayBox()
  {
   Console.WriteLine("Lenghth: {0}, Width: {1}, Height: {2}", length, width, height);
  }

// constructor
public Box(int theLength, int theWidth, int theHeight)
   {
    length = theLenghth;
    width = theWidth;
    height = theHeight;
   }
}

public class Tester
{
  static void Main()
  {
     Box bocObject = new Box(4, 8, 3);
     boxObject.DisplayBox();
  }
}

}




what i do understand from this bit of code is that im giving int length width and height values by the public method called Box, which has inside of its parentheses variables such as int theLength, int theHeight etc. . in that method we're also stating that length = theLength etc. , why make it so messy? i just cant get it. why not just give private int length its value, such as 10 and thats it?
is this because we're trying to implement OOP? making it easier to be maintained later? cause when i have a method that is in charge of giving the int length a value, once i'd like to change it i'll just have to go to that method instead of changing it in many different places? (but yet again, cant we make a public int that would be used in all classes?)
so an explanation about that would be great.

then comes the Initializers. basically the code in their example is pretty much the same as the one above, but this time they've given private int height a value, = 6 at the beginning, and at the main method the only thing changed was

static void Main()
{
Box boxObject = new Box(4, 8);
boxObject.DisplayBox();
}

so basically we get the same output in both cases (only difference is in heights value). why use constructors instead of initializers?
the way it seems to me, giving int height length and width a value at the beginning would have been much easier, rather than making a whole new method for it.

hope im not asking for too much but i really didnt get this part :(
thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: can't seem to understand constructors and initializers

#2 blixna_waka  Icon User is offline

  • D.I.C Head

Reputation: -5
  • View blog
  • Posts: 60
  • Joined: 14-July 10

Re: can't seem to understand constructors and initializers

Posted 16 July 2010 - 08:53 AM

Constructors allow for greater flexibility in code. Consider using the constructor with user input... the user could input their own dimensions into the code from the command line, and it would be output back to them. This is key when you get into object oriented programming, especially when the output of your program is intended to be different every time. Constructors can also be used for restriction on the flipside. If you want to make sure that one dimension stays the same, and can't be controlled by the user, you'd put that in as the first variable in the constructor, and then put in the other two uninitialized. I hope this helps you to understand the importance of using constructors, as you WILL be using them quite frequently.
Was This Post Helpful? 1
  • +
  • -

#3 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: can't seem to understand constructors and initializers

Posted 16 July 2010 - 08:57 AM

You would want to use initializers when you are fairly certain that in cases when creating an object you want that value already set.

Using constructors is a really good practice because it's less code for you to write!

Compare the following:

public class Person
{
    public string Name { get; set; }
    public string Age {get; set; }
}

//And to create a person you would go:
Person myFriend = new Person();
myFriend.Name = "Sergio";
myfriend.Age = "20";




Now compare it to this!

public class Person
{
    public string Name { get; set; }
    public string Age {get; set; }

    public Person(string name, string age)
    {
        Name = name;
        Age = age;
    }
}

//And using it.
Person myFriend = new Person("Sergio", "20");



See the difference? It produces cleaner code and easier to see what you're doing.
Was This Post Helpful? 4
  • +
  • -

#4 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4498
  • View blog
  • Posts: 7,850
  • Joined: 08-June 10

Re: can't seem to understand constructors and initializers

Posted 16 July 2010 - 09:06 AM

*
POPULAR

The constructor is a special method, called whenever you use the keyword new.. Since it's the method that's going to happen when you create a new instance of that class, you want to put all your setup logic in that constructor.

In your example, your object is a box. Well, what information defines a box? It's length, width, and height. So for every new box we create, we want to make sure that we make them with those properties.

An important thing to understand is that when you are writing a class, you're not creating one copy of it. A class is a blueprint for creating objects. So in your Box class there, you're not actually creating a box. You're writing instructions for the creation of boxes.

So when you instantiate a new box, you need to tell the box each of its dimensions. The line:
Box bocObject = new Box(4, 8, 3);

Is actually going to the constructor, and telling it "Make me a new box, with a length of 4, width of 8, and height of 3."

This post has been edited by insertAlias: 16 July 2010 - 09:06 AM

Was This Post Helpful? 6
  • +
  • -

#5 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5535
  • View blog
  • Posts: 11,861
  • Joined: 02-June 10

Re: can't seem to understand constructors and initializers

Posted 16 July 2010 - 09:20 AM

First things first... Remember that everything 'thing' you make is an instance of an object. And one object is quite often a collection of smaller objects, just like in the real world.

There is the hypothetical concept of a truck. But the Dodge Ram in my driveway is an *instance* of that concept that was constructed.
Dodge.Ram is a concept.
Dodge.Ram myRam4WD = new Dodge.Ram("abc1234"); is an instance of a Ram that was constructed -AND- the constructor method accepted the VIN in the process.
System.Windows.Form is a concept of a form.
Form myMainWindow = new Form(); is an instance of a form that has been constructed.

Q: Why do we have constructors that take parameters instead of just always making an object *then* setting the parameters?
A: A constructor with no parameters means a blank object with no defaults. Maybe that's dangerous.
A: So we can have overloaded constructors that will perform different setups depending on which parameters are supplied. If I make a constructor with just the form name then I use the default size. If I make a constructor with form name, and an int maybe I auto-close the form using the int as a timer.

Q: Why do we use complex properties instead of just making a simple variable public?
A: Variables don't perform actions.
EX:

public int NewWidth;  // If I change this number from some action what happens?  Nothing
ResizeForm(); // which means I have to always know to set the new size THEN run the resize method.



But properties have get and set which are methods of runnable code that can think and do things for us.
public int NewWidth
{
   get
   {
     return this.width;
   }
   set
   {
       if (value > MaxSizeAllowed) value = MaxSizeAllowed; // Disallowing an illegal size
       if (value < MinSizeAllowed) value = MinSizeAllowed; // Disallowing an illegal size
       this.width = value;
       textbox1.width = this.width - 200; // Change the textbox width to fit the form.
       button1.Location = new Point(textbox1.Bounds.Right + 10, button1,Location.Y); // Move the button to the right of the new textbox width.
       picturebox1.Location = new Point(button1.location.X, button1.bounds.bottom + 10); // Move the picture just below the new button location
    }
}

Was This Post Helpful? 4
  • +
  • -

#6 lookitstom  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 28
  • Joined: 12-July 10

Re: can't seem to understand constructors and initializers

Posted 16 July 2010 - 10:33 AM

you guys are amazing
thanks to all of you, great people doing a great job :)

i hope that in a couple of months i'll be able to do the same thing ^.^

explanations were fantastic, so thanks again, really helped me out!
Was This Post Helpful? 2
  • +
  • -

#7 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4498
  • View blog
  • Posts: 7,850
  • Joined: 08-June 10

Re: can't seem to understand constructors and initializers

Posted 16 July 2010 - 10:35 AM

Glad to help people that actually want to learn.
Was This Post Helpful? 3
  • +
  • -

Page 1 of 1