Alex Rivera | Logout

How to return a value using constructor in c#?

Asked 2012-11-21T16:26:00.693
19

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.

Edit
Report

2 Answers

38

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!");
      }
    }
}
answered 2012-11-21T16:27:22.697
1

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
}
answered 2012-11-21T16:28:54.633

Your Answer