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.
A constructor can not return a value because a constructor implicitly returns the reference ID of an object, and since a constructor is also a method and a method can't return more than one values.
By definition there is no possibility of returning a value from a constructor. A constructor does not support any return type.
Constructor methods do not have a return type (not even void). C# provides a default constructor to every class.
A constructor doesn't return anything.
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!");
}
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With