Constructors

+1 Tiby P · January 17, 2015
I don't understand the c# constructors.. can someone say more things in detail or a link or something ?

Post a Reply

Replies

Oldest  Newest  Rating
0 Branislav Lazic · January 17, 2015
Can you just use a google?
0 Orkun Erbil · January 17, 2015
Constructors do objects' default information. When you create an object, that you created constructors for a class, your object's properties will be exactly the same in the constructor of that class. This is basic information for a constructor.           (Sorry for my English)

Can you say what you want to know from us clearly ? :)            
+1 Eugene Botma · January 18, 2015
A constructor is a method that gets executed when you instantiate an instance of an object, but unlike a method, it cannot have a return type.

Generally, a constructor is used to set the initial data for an object as Orkun mentioned, but like other methods, it can be used to calculate a certain value first. It can, also like other methods, have overloaded versions. 

Constructors are pretty useful, becuase a lot of the times there are a few things that need to be calculated or determined when instantiating an object, so having the constructor do the calculations is easier and less code than having to do the calculations yourself every time you want to instantiate an object, Especially is someone else is going to use your code and does not necessarily know what or how to do those calculations.

Also
myObject tmp = new myObject (value1, value2, value3, value 4);

//is much neater

myObject tmp = new myObject();
tmp.value1=value1;
tmp.value1=value2;
tmp.value1=value3;
tmp.value1=value4;
+1 Branislav Lazic · January 18, 2015

"A constructor is a method that gets executed when you instantiate an instance of an object, but unlike a method, it cannot have a return type."




Wrong! Constructor is not a method. It's a piece of code that executes and RETURNS instance of class although it doesn't have return type. If constructor is not explicitly defined, it's presumed that default constructor will be invoked:

public class MyClass {
   
   // Default c-tor
   public MyClass() {

   }
}


It can take arguments as method.
When you create an instance (object) of your class you are invoking constructor (or one of constructors in case if multiple constructors are defined). Same as in case of methods, you cannot define two constructors with same parameters list. Scope of constructor is mostly public. Although it can also be private. If scope of constructor is private, it can be invoked only withing class. Why would you even create private constructor? I.e. in case of singleton pattern. 
+1 Eugene Botma · January 18, 2015
My bad, I meant to say: "A constructor is LIKE a method that...."
  • 1

C#

107,126 followers
About

C# is an object-oriented language designed for improving the development of web applications.

Links
Moderators