Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can i make a constructor to return value in my C# program.
Posted
Comments
Simon_Whale 13-Jan-15 6:56am    
I think you need to explain in a bit more detail of what you are trying to achieve.

As I think using a property would be better suited if you want to put in a value, then have a method work on that value and it can then be retrieved by the property.

Constructor can not have return type. You can't even use void. Use parameter constructor with ref keyword instead.
 
Share this answer
 
You can't.
A constructor is a specific type of method that already has a return value - the new instance of the class you are creating.

You could pass a ref or out parameter to the constructor, but that would be rather unusual:
C#
public class MyClass
    {
    static int instanceCount = 0;
    public MyClass(ref int val)
        {
        val = ++instanceCount;
        }
    }
 
Share this answer
 
A constructor does not support any return type. Not even void. The implicit return type by default is the class type in which it is declared. You can use 'ref' or 'out' parameter as mentioned by OriginalGriff.
 
Share this answer
 
Even if ref or out parameters could be used as mentionned in other solution, it would be a bad design.

One design principle is that a piece of code should have a single responsability. Thus, you are probably trying to do to much from the constructor.

In case like that, you have a few alternatives. One of those would be to simply call a method (or property) of the object to get the information that would have been stored in the class.

Another one would be to split the construction into multiple phases so that another fonction is used to complete the initialization and retyurn the value.

A third alternative would be to make the constructor private and use a static function to create the object. Combined with my first alternative, you would essentially have the same effect as having a constructor that would returns a value.

By the way, how would you get the value of such constructor if you have one as the return value is implicitly a new object of the appropriate type.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900