Sanmuga Nathan
Sanmuga Nathan

Reputation: 185

How to return a value using constructor in c#?

I follow a convention that I won't use any print statements in classes, but I have done a parameter validation in a constructor. Please tell me how to return that validation which I've done in the constructor to the Main function.

Upvotes: 19

Views: 42161

Answers (6)

Pawel Czapski
Pawel Czapski

Reputation: 1864

I think my approach might be useful also. Need to add public property to constructor, then you can access this property form other class, as in below example.

// constructor
public class DoSomeStuffForm : Form
{
    private int _value;

    public DoSomeStuffForm
    {
        InitializeComponent();

        // do some calculations
        int calcResult = 60;
        _value = calcResult;
    }

    // add public property
    public int ValueToReturn
    {
        get 
        {
            return _value;
        }
    }
}

// call constructor from other class
public statc void ShowDoSomeStuffForm()
{
    int resultFromConstructor;

    DoSomeStuffForm newForm = new DoSomeStuffForm()
    newForm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
    newForm.ShowDialog();

    // now you can access value from constructor
    resultFromConstructor = newForm.ValueToReturn;

    newForm.Dispose();
}

Upvotes: 1

Adil
Adil

Reputation: 148150

Constructors do not have a return type, but you can pass values by reference using the ref keyword. It would be better to throw an exception from the constructor to indicate a validation failure.

public class YourClass
{
    public YourClass(ref string msg)
    {
         msg = "your message";
    }

}    

public void CallingMethod()
{
    string msg = string.Empty;
    YourClass c = new YourClass(ref msg);       
}

Upvotes: 5

nVn
nVn

Reputation: 21

Make a Constructor with Out parameter and send your return value via same.

public class ClassA
{
    public ClassA(out bool success)
    {
        success = true;
    }
}

Upvotes: 2

Adi Lester
Adi Lester

Reputation: 25211

When a constructor receives an invalid argument, it's common to throw an exception. You can then catch this exception and parse the data it contains.

try
{
    int input = -1;
    var myClass = new MyClass(input);
}
catch (ArgumentException ex)
{
    // Validation failed.
}

Upvotes: 0

user27414
user27414

Reputation:

A constructor returns the type being instantiated, and, if necessary, can throw an exception. Perhaps a better solution would be to add a static method to try creating an instance of your class:

public static bool TryCreatingMyClass(out MyClass result, out string message)
{
    // Set the value of result and message, return true if success, false if failure
}

Upvotes: 1

Oded
Oded

Reputation: 499142

The constructor does return a value - the type being constructed...

A constructor is not supposed to return any other type of value.

When you validate in a constructor, you should throw exceptions if the passed in values are invalid.

public class MyType
{
    public MyType(int toValidate)
    {
      if (toValidate < 0)
      {
        throw new ArgumentException("toValidate should be positive!");
      }
    }
}

Upvotes: 38

Related Questions