-5
using System;
class Program
{
    class Person {
        protected int Age {get; set;}
        protected string Name {get; set;}
    }
    class Student : Person {
        public Student(string nm) {
            Name = nm;
        }
        public void Speak() {
            Console.Write("Name: "+Name);
        }
    }
    static void Main(string[] args)
    {
        Student s = new Student("David");
        s.Speak();
    }
}

--->Output: Name:David

In the above code we have 'get' and 'set' methods used..

Now...

using System; class Program { class Person {

        protected string Name;
    }
    class Student : Person {
        public Student(string nm) {
            Name = nm;
        }
        public void Speak() {
            Console.Write("Name: "+Name);
        }
    }
    static void Main(string[] args)
    {
        Student s = new Student("David");
        s.Speak();
    }
}

--->Output: Name:David

Here i have removed the 'get' and 'set' methods but the output was same. Then what is the use of those methods?

Siva Teja
  • 3
  • 4
  • 1
    Your question is unclear. There are no methods named `get` or `set` in the code you posted. – Jörg W Mittag Feb 12 '17 at 15:57
  • an item declared on a class without `get` and `set` is considered a field, not a propery; fields are handled differently. the `{get;set;}` without actual functions is called "auto property accessors", making the item a property with an automatic backing field. – Claies Feb 12 '17 at 16:00
  • 1
    as an example, `Student.Name` would work in the first example, but would not work in the second example. – Claies Feb 12 '17 at 16:02

1 Answers1

2

You can make sure that no wrong inputs are made, or basically execute additional code whenever the property is changed...

Anton Ballmaier
  • 876
  • 9
  • 25