Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Why Is It Recommend To Set Fields Using Properties?

$
0
0
So I frequently for example see code like this

 private string number_one;
        private string number_two;

        private string SetFistNumber
        {
            set { this.number_one = value; }
        }
        private string SetSecondNumber
        {
            set { this.number_two = value; }
        }

        public CGiganticMath(string first_numer, string second_number)
        {
            this.SetFistNumber = first_numer;
            this.SetSecondNumber = second_number;
        }
        



I've seen this but WHY use this when you can just use the constructor to set the fields like

 private string number_one;
        private string number_two;


        public CGiganticMath(string first_numer, string second_number)
        {
            this.number_one = first_numer;
            this.number_two = second_number;
        }
        



Or you can just use properties

        private string SetFistNumber
        {
            get; set;
        }
        private string SetSecondNumber
        {
           get; set;
        }

        public CGiganticMath(string first_numer, string second_number)
        {
            this.SetFistNumber = first_numer;
            this.SetSecondNumber = second_number;
        }
        




And then just use that properties. OR you can now use a constructor at all. Frequently I've heard the rhetoric that you should use properties to set fields though like in the top example but why? Doesn't that just make the program slower when you could just set a field or property directly or directly through the constructor?

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>