0

I need someone to help me understanding this bit of c# code:

public Teacher[] Teachers { get; set; }

I can see this is an array but is it ok to use get, set here instead of :

public Teacher[] Teachers = new Teacher[4];
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
Tuhin
  • 25
  • 1
  • 7
  • I don't understand your question. Do you mean Is it ok to use fields instead of properties? – Sriram Sakthivel May 03 '15 at 09:41
  • This is called auto-implemented properties. [read here.](https://msdn.microsoft.com/en-us/library/bb384054.aspx) – Zohar Peled May 03 '15 at 09:42
  • We were asked to create an array of Teacher and I saw someone wrote it like properties and I paste this code into Visual Studio and it does not complain. SO I am confused about it. – Tuhin May 03 '15 at 09:43
  • Take a look at [this](http://stackoverflow.com/questions/4142867/what-is-difference-between-property-and-variable-in-c-sharp) and [this](http://stackoverflow.com/questions/6542827/honestly-whats-the-difference-between-public-variable-and-public-property-acce) question. – molnarm May 03 '15 at 09:44

1 Answers1

0
public Teacher[] Teachers { get; set; }

This creates a property called Teachers of type Teacher[].

public Teacher[] Teachers = new Teacher[4];

This creates a field called Teachers of type Teacher[] and initializes it will a length of 4.

You can initialize a property in the classes constructor:

public class TestClass
{
    public Teacher[] Teachers { get; set; }

    public TestClass()
    {
       Teachers = new Teacher[4];
    }
}

Read here about the difference between a property and a field.

Community
  • 1
  • 1
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • I think it would be a bit more correct if you said that your first sample code line created _both_ a property and a (hidden) field. – RenniePet May 03 '15 at 09:50