How to return a value using constructor in c#?

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

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

提交回复
热议问题