How to return a value using constructor in c#?

后端 未结 6 954
温柔的废话
温柔的废话 2021-01-04 03:42

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

6条回答
  •  醉话见心
    2021-01-04 04:15

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

提交回复
热议问题