Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return type of a constructor in C#?

Tags:

c#

constructor

I have asked this question for Java on this link

I got some answers in java.Now i want to know it in C#.

As we know the we do not have to add any return type to a C# constructor.

class Sample{   .....   Sample(){     ........   } } 

In Objective C, if we create a constructor, it returns a pointer to its class. But it is not compulsory, I think.

AClass *anObject = [[AClass alloc] init];//init is the constructor with return type a pointer to AClass 

Similarly, Is the constructor converted to a method which return a reference to its own class??

Like this:

class Sample{     .....     Sample Sample(){       ........        return this;     } } 

Does the compiler add a return type a reference to same class to constructor? What is happening to a constructor? Any reference to study this?

like image 665
sonu thomas Avatar asked Jan 17 '12 11:01

sonu thomas


People also ask

What is return type of constructor?

A constructor doesn't have any return type. The data type of the value retuned by a method may vary, return type of a method indicates this value. A constructor doesn't return any values explicitly, it returns the instance of the class to which it belongs.

Why constructor has no return type?

So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime. Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.


2 Answers

According to the C# 4.0 Language Specification, section 1.6:

Instances of classes are created using the new operator, which allocates memory for a new instance, invokes a constructor to initialize the instance, and returns a reference to the instance.

It is the new operator who is responsible of allocating memory, passing a reference of the newly allocated object to the constructor and then returning a reference to the instance. This mechanism is also explained in section 7.6.10.1:

The run-time processing of an object-creation-expression of the form new T(A), where T is class-type or a struct-type and A is an optional argument-list, consists of the following steps:

  • If T is a class-type:

    • A new instance of class T is allocated. If there is not enough memory available to allocate the new instance, a System.OutOfMemoryException is thrown and no further steps are executed.

    • All fields of the new instance are initialized to their default values (§5.2).

    • The instance constructor is invoked according to the rules of function member invocation (§7.5.4). A reference to the newly allocated instance is automatically passed to the instance constructor and the instance can be accessed from within that constructor as this.

  • […]

This would mean that the constructor per se has no return type (void).

like image 90
InBetween Avatar answered Oct 11 '22 13:10

InBetween


InBetween's answer is correct. I too disagree with what was discussed in the MSDN forum. If we look at a very simple code sample like the one below:

void Main() {    var a = new A();    var message = a.GetAs(); }  public class A {      private readonly string someAs;      public A()     {         someAs = "AaaaaAAAAAaaAAAAAAAaa";         return;     }      public String GetAs()     {         return someAs;     } } 

and the corresponding IL:

IL_0000:  newobj      UserQuery+A..ctor IL_0005:  stloc.0      IL_0006:  ldloc.0      IL_0007:  callvirt    UserQuery+A.GetMessage  A.GetMessage: IL_0000:  ldarg.0      IL_0001:  ldfld       UserQuery+A.someAs IL_0006:  ret           A..ctor: IL_0000:  ldarg.0      IL_0001:  call        System.Object..ctor IL_0006:  ldarg.0      IL_0007:  ldstr       "AaaaaAAAAAaaAAAAAAAaa" IL_000C:  stfld       UserQuery+A.someAs IL_0011:  ret 

then it becomes immediately clear, that the .ctor returns void. (This can also been seen easily if you try to return something from the constructor, i.e. if you do something like public A() { return this; } the compiler will complain and say something like "Since A() returns void, a return keyword must not be followed by an object expression.")

Further: You can see that this expression new A() gets translated to the following IL: newobj UserQuery+A..ctor. The "Common Language Infrastructure Reference" says the following about newobj (section 4.20):

The newobj instruction allocates a new instance of the class associated with constructor and initializes all the fields in the new instance to 0 (of the proper type) or null as appropriate. It then calls the constructor with the given arguments along with the newly created instance. After the constructor has been called, the now initialized object reference is pushed onto the stack.

(By way of comparison with Objective-C: new/newobj is the analog to the alloc message and the constructor the analog to the initmessage.)

So it really is the new operator that returns a reference to the newly constructed object, not the constructor itself.

like image 38
afrischke Avatar answered Oct 11 '22 14:10

afrischke