How to return a value using constructor in c#?

后端 未结 6 910
温柔的废话
温柔的废话 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:04

    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.
    }
    

提交回复
热议问题