How to return a value using constructor in c#?

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

    I think my approach might be useful also. Need to add public property to constructor, then you can access this property form other class, as in below example.

    // constructor
    public class DoSomeStuffForm : Form
    {
        private int _value;
    
        public DoSomeStuffForm
        {
            InitializeComponent();
    
            // do some calculations
            int calcResult = 60;
            _value = calcResult;
        }
    
        // add public property
        public int ValueToReturn
        {
            get 
            {
                return _value;
            }
        }
    }
    
    // call constructor from other class
    public statc void ShowDoSomeStuffForm()
    {
        int resultFromConstructor;
    
        DoSomeStuffForm newForm = new DoSomeStuffForm()
        newForm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        newForm.ShowDialog();
    
        // now you can access value from constructor
        resultFromConstructor = newForm.ValueToReturn;
    
        newForm.Dispose();
    }
    

提交回复
热议问题