Reputation: 5796
I'm learning C# now and a beginner in the programming world. I have a book called The Complete Reference by Herbert Schildt. So far its a good book and I'm in the middle of learning about methods and constructors.
I'm quite confused what's the difference of methods and constructors. Because in the book it has almost the same example. I don't know how to differentiate them. I would appreciate your idea. By the way I have several definition here of both, I just would like to know how to differentiate them
Thanks for your help
Cheers
Upvotes: 14
Views: 37304
Reputation: 1
A constructor is a special method that usually has the same name as the class, and we can use it to set the values of the members of an object to either default or user-defined values.
Whereas, a method is a programmed procedure that is defined as part of a class and included in any object of that class. These definitions give an idea about the fundamental difference between constructor and method.
Return type To add to this, the constructor has no return type whereas method can return a value or not. Hence, this is another difference between constructor and method.
Default An important difference between constructor and method is that the program will call the default constructor in case the programmer does not write a constructor. However, there are no default methods.
Name A constructor has the same name as the class name while a method can have any name other than keywords.
Invocation One other difference between constructor and method is that the constructors implictly invoke whereas the methods invoke explicitly.
Usage Furthermore, constructor helps to initialize an object whereas a method helps to exhibit the functionality of an object.
Conclusion Constructor and method are related to OOP. The main difference between constructor and method is that a constructor is a special method in a class that initializes objects of that class while a method is a procedure or a function that executes a set of instructions associated with a class.
Upvotes: 0
Reputation: 2880
Adding to previous technical answers, Constructor is supposed to provide necessary minimal initialization that make sure you can use that particular class i.e. object, moreover constructor should make class self sufficient.
So everything we design, we code is to solve real world problems. So if you want to Read you might want to have at least one book. So if Read
is your class, you probably want to initialize list of book there. So books can be static data or from XML or from any other sources.
Upvotes: 0
Reputation: 137
In C# a constructor is called upon class instantiation. It has no return type as it does not return anything. I usually use it to instantiate class properties that require an object reference, like Collection objects, custom objects (classes), other objects that require instantiation. A C# constructor is not required to be written by the programmer. If you don't write one, the compiler will generate one automatically and then call it.
Constructors can also be overloaded. So you can have several constructors each with different parameter types. If you do happen to overload you constructor, be sure to include an empty constructor with no parameters in case there are any calls to the class that do not pass in any parameters.
public class MyClass {
public List<int> MyIntList { get; set; }
MyClass() {
}
MyClass(int i) {
MyIntList = new List<int>();
MyIntList.Add(int i);
}
}
Upvotes: 0
Reputation: 1
Constructer is special method of the class that initialize class field. Constucter name is same name as class name.Which does not have return type. When instance is created that time constructor is called. Without constructor memory cannot allocated if developer is failed to define constructor then implicit constructor called and initialize field with fixed value or default value of the data type.
Upvotes: 0
Reputation: 171
Constructors are special type of methods. Whenever a new object is created in the memory this method is called automatically. Also constructor does not have any return type while other methods have return type.
Upvotes: 0
Reputation: 1931
Constructors are special methods, used to initialize your class members with different signatures/parameters
Upvotes: -1
Reputation: 23796
A constructor only works when you create a new instance of a class. This is the very first method to run on an instance, it has to run, and it runs exactly once.
A method on an instance can be called anywhere between zero times to infinite times on an instance once it is created.
A constructor is run implicitly. When a new instance of a class is created, it runs automatically. A method is run explicitly. It has to be called either from some outside source or from a method -or a constructor- in the class.
A constructor is intended to be used for wiring. In the constructor, you want to avoid doing actual work. You basically prepare the class to be used. A method is intended to do actual work.
public class MyType
{
private SomeType _myNeeds;
// constructor
MyType(SomeType iWillNeedThis)
{
_myNeeds = iWillNeedThis;
}
// method
public void MyMethod()
{
DoSomethingAbout(_myNeeds);
}
}
Upvotes: 24
Reputation: 61
Constructor will be automatically invoked when an object is created whereas method has to be called explicitly. Constructor needs to have the same name as that of the class whereas functions need not be the same. There is no return type given in a constructor signature (header). It is same as that of the Class There is no return statement in the body of the constructor.
Example:
class Widget //Some Class "Widget"
{
int _size;
int _length;
// Declaring a Constructor, observe the Return type is not required
public Widget(int length)
{
this._length = length;
}
// Declaring a Method, Return type is Mandator
public void SomeMethod(int size)
{
this._size = size;
}
}
//Calling the Constructor and Method
class Program
{
static void Main()
{
//Calling the Constructor, Observe that it can be called at the time the Object is created
Widget newObject = new Widget(124);
//Calling the Method, Observe that the Method needs to be called from the New Object which has been created. You can not call it the way Constructor is called.
newObject.SomeMethod(10);I
}
}
Upvotes: 6
Reputation: 41
Note that the material of constructor is method. it means that constructor is a special type of method, its name is the same as class exactly but does not have output paramether.Constructor is called during creation of the object from class.
Public class person()
{
public person()
{
}
}
Upvotes: 4
Reputation: 41136
class invariants
A class is responsible to preserve invariants - that is: a class makes guarantees to the caller, such as "object.weight
is never negative", "there are no duplicates in the list of names", etc.
A method manipulates an existing object, thus can rely on class invariants being guaranteed at method entrance. A method needs to make sure it transforms a valid state into another valid state.
A constructor pulls the object out of thin air, thus must create the invariants.
object existance
When a constructor throws an exception, the object is assumed to have never existed. Thus, e.g. a finalizer will never run. The consequences are comparedly weak in C#, they are more prominent in languages with deterministic destruction, such as C++.
Upvotes: 0
Reputation: 5919
In terms of what they're allowed to do, constructors don't differ all that much from methods. The main conceptual difference between a method and a constructor is its purpose.
A constructor brings an object into a valid, usable state, and is called only once, at the beginning. A method changes an object from one valid state to another. (Okay, some methods only retrieve information, they're not required to change the state of an object).
Edit: It occurs to me that, particularly for C#, the above explanation might be confusing, as immutable objects aren't exactly uncommon idioms in the language, so a lot of objects the OP will encounter won't have a changeable state. Complex concepts often have one-line explanations that are simple, elegant and wrong.
Upvotes: 2
Reputation: 179219
The constructor method name has the same name as the class. Also, it does not have a return type. Or, if you will, the constructor method itself has no name, but the return type is the class type.
public class Foo
{
// Constructor
public Foo()
{ }
public void Bar()
{ }
}
Upvotes: 4
Reputation: 7297
In terms of how they operate on the object, they behave similarly. A constructor is a method of the object, but it's a special method.
What makes it special is how it gets called from outside. A constructor is called as part of the process of creating the object. Normal methods get called explicitly on the object (after it is done being created).
Upvotes: 0
Reputation: 170569
A constructor is an instance method with special meaning - specifically it is called internally when creating an instance of the corresponding class with new. That's the key difference.
Other minor differences are that the constructor must have the same name as the class it belongs to and it can't have any return value, even void.
Upvotes: 5
Reputation: 9539
A constructor is a method.. a special method that is being called upon "construction" of the class.
Definition: A constructor is a class member function in C++ and C# that has the same name as the class itself.
The purpose of the constructor is to initialize all member variables when an object of this class is created. Any resources acquired such as memory or open files are typically released in the class destructor.
From About.com
Upvotes: 15