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.

6 Answers 6

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!");
      }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

oohh, I wish I could up vote thousand times. It's so tiresome with that permissive validation style that is spreading like cancer.
@jgauffin - What style do you mean?
For instance using DataAnnotation attributes on your domain/business models. i.e. allowing objects to have invalid information and relying on the calling code to make sure that everything is validated and correct. you know.. violating encapsulation.
@jgauffin - I see. Annotating but not checking that the invariants are actually held.
5

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);       
}

1 Comment

That you can doesn't mean you should.
3

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

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

1 Comment

Your class is too fragile if it comes to this.
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
}

Comments

1

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();
}

Comments

0

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.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.