Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a value using constructor in c#?

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.

like image 829
Sanmuga Nathan Avatar asked Nov 21 '12 16:11

Sanmuga Nathan


People also ask

Can we return a value from constructor?

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.

Can constructor return a value in C?

By definition there is no possibility of returning a value from a constructor. A constructor does not support any return type.

What is return type of constructor in C?

Constructor methods do not have a return type (not even void). C# provides a default constructor to every class.

What should be returned from a constructor?

A constructor doesn't return anything.


2 Answers

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!");
      }
    }
}
like image 142
Oded Avatar answered Oct 20 '22 19:10

Oded


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);       
}
like image 32
Adil Avatar answered Oct 20 '22 21:10

Adil