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