Michal_Drwal
Michal_Drwal

Reputation: 536

C# get set accessors

I have a strange question. I'm trying to understand how to use accesssors correctly. I get the idea of using them with private and public variables in classes but C# 3.0 allows us to use them with only public ones (i.e)

public string Email {get; set;}

So, I'm writing an app - this a part of my code:

public class Customers
{
   public string Telephone;
   public string Email {get; set;}
   public void LoadCustomer(string _name)
   {
       DataSet dataSet = new DataSet();
       dataSet.ReadXml("Customers.xml");


       XDocument doc = XDocument.Load("Customers.xml");
       XElement root = doc.Root;
       for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
       {

           var Klient = from wpisy in root.Elements("Customer")
                        where wpisy.Element("Name").Value.Equals(_name)
                        select wpisy;
           Telephone = Klient.First().Element("Telephone").Value;
           Email = Klient.First().Element("Email").Value;

       }
    }
}

private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
    Customers customer = new Customers();
    customer.LoadCustomer(name);
    txt_Telephone.Text = customer.Telephone;
    txt_Email.Text = customer.Email;
}

As you can see, I have a class and a method which calls the class when the window is opened. Everything works whenever I use the accessors:

public string Email {get; set;}

or I don't:

public string Telephone;

So, my question (maybe silly) is what's the point of using the accessors with such public variables since there's no difference when I use them or not?

Upvotes: 3

Views: 3111

Answers (1)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

There is no functional difference between the two. However, public string Telephone; is a codesmell because it exposes your value with its plain data to the outside world and not trough an (implicit) accessor.

This means that you will never be able to add some sort of validation rule like this without breaking existing code:

private string _email;
public string Email {
 get { return _email }
 set {
  if(value.Contains("@") { _email = value }
 }
}

To the outside world this is still used as MyClass.Email, but you can add logic behind it which wouldn't be possible if you would simply use a field instead of a property.

Upvotes: 3

Related Questions