+ 1

what is the difference? get and set Not needed... "Bob" is displayed everywhere

1.With Get and Set: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { class Person { private string name; public string Name { get { return name; } set { name = value; } } } static void Main(string[] args) { Person p = new Person(); p.Name = "Bob"; Console.WriteLine(p.Name); } } } 2.Without Get and Set using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoloLearn { class Program { class Person { private string name; public string Name; } static void Main(string[] args) { Person p = new Person(); p.Name = "Bob"; Console.WriteLine(p.Name); } } }

20th Dec 2020, 1:00 AM
SLiver
SLiver - avatar
3 odpowiedzi
+ 5
SLiver You have declared a public variable Name that's why it's working and Bob is printing. Try to run program without public string Name then you can't get output without set and get. It will through an error.
20th Dec 2020, 3:38 AM
A͢J
A͢J - avatar
+ 2
Yes, get and set are used to make the string Name more secured. Let say you want to secure a variable like password, then you cannot make it public. In such cases you can use get and set to limit the access and if you don't want your user to enter a vulnerable password which include some special characters. Then you set some rules in set such that it convert special characters which makes password vulnerable to a valid password using some defined escape sequences.
20th Dec 2020, 3:45 AM
Padala Vamsi
Padala Vamsi - avatar
+ 2
1 is a property 2 is a field In your example they do the same. The private variable name in 2 is not used. However if you use a property it can easily be secured by adding code to the setter. With a field you can't do this. So although you do not want to do this when the first time you write the code. Do use properties just in case, you want to secure it in the future.
20th Dec 2020, 8:25 AM
sneeze
sneeze - avatar