Help - Search - Members - Calendar
Full Version: Constructors? C# Question
Sal's RuneScape Forum > Everything... Not RuneScape > Tech Talk > Programming & Web Development
Roy
What are constructors and destructors, what do they do and are they really necessary?

Note: if possible no links to some tutorial unless it really explains it good...
cjgone
They allow you to create objects of a specific type... I don't do C#, but if you've ever done Java, it would be like:

CODE
Box blah = new Box( 10,20,30,40); // create a new object box

public class Box {

public Box ( int x, int y, int x2, int y2)
{
//constructor code here
}
}


Never used a deconstructor, so I dunno how to use it. I'm guessing it allows you to delete the object. Just a guess.
Kaibamanjrs
Constructors are instructions that should be run when an instance of the parent class is created.

For example, if i had this (public MyObjectType is our constructor)
CODE
class MyObjectType {
private int x;
private int y;
public MyObjectType (int x1, int y1) {
x = x1;
y= y1;
}
public void DoSomeCalculation () {
Console.WriteLine("This is my text" + x + y);
}
}


and then somewhere else I did this
CODE
MyObjectType myInstance = new MyObjectType (20,40);
myInstance.DoSomeCalculation ();

I should get
This is my text2040

I might have made an error somewhere, but this is basically how it works.

As for destructors, they are used for garbage collecting. When it is deemed necessary to get rid of it ( it runs out of scope or something) you could have special cleanup instructions in a destructor (which would be ~ followed by the name of your constructor) you must have a constructor if you have a destructor.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.