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 validatio
Make a Constructor with Out parameter and send your return value via same.
public class ClassA
{
public ClassA(out bool success)
{
success = true;
}
}
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();
}
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);
}
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
}
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.
}
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!");
}
}
}