0

I have read msdn article about properties. They show that example of property:

// Declare a Name property of type string:
    public string Name
    {
        get 
        {
           return myName; 
        }
        set 
        {
           myName = value; 
        }
    }

Then they say:

Once the properties are declared, they can be used as if they were fields of the class.

What would be the difference if they just left:

public string Name;

If I had a field: private string name and wanted to have only getter? Should I declare

public string GetName(){return name;} or should use those properties somehow?


Could somebody tell me what is wrong with that example:

 private int age;
 public void setAge(int age){
   if(age < 100) 
   this.age = age;
}
Yoda
  • 17,363
  • 67
  • 204
  • 344

1 Answers1

1

This from Clr Via C#

Field A data variable that is part of the object’s state. Fields are identified by their name and type.

Property To the caller, this member looks like a field. But to the type implementer, it looks like a method (or two). Properties allow an implementer to validate input parameters and object state before accessing the value and/or calculating a value only when necessary. They also allow a user of the type to have simplified syntax. Finally, properties allow you to create read-only or write-only “fields."

  • Ok but why just don't define getter and setter for the field? – Yoda Jan 12 '14 at 18:00
  • Because you can check validation from central location –  Jan 12 '14 at 18:01
  • What is central location? One should define setter and getter in the same class that field is declared. – Yoda Jan 12 '14 at 18:02
  • for example you must check Age Property that not grater than 100 so you can check this in setter and other class if set Age value grater than 100 you prevent it –  Jan 12 '14 at 18:06
  • Yes, exacly that's my point. That's the reason I don't get properties. You can do it without them `private int age; public void setAge(int age){if(age < 100) this.age = age;}` Why should I use properties? – Yoda Jan 12 '14 at 18:11
  • 1
    Yes in java you dont have Property Like C# you should write set and get manually –  Jan 12 '14 at 18:14
  • Ok so why this is bad in C#. I really do want to understand properties. It's not the first time I am trying. – Yoda Jan 12 '14 at 18:15
  • in C# or other is bad that manipulate field from out of class –  Jan 12 '14 at 18:16
  • `setAge(int age)` is in the same class as field. – Yoda Jan 12 '14 at 18:19