Public – Class or member can be accessed by any code.

Private  – Class or member can only be accessed by parent class.

Protected – Class or member can only be accessed by parent class or derived class.

Internal – Class or member can only be accessed by code inside the same assembly.

Classes are internal by default.

Methods and properties are private by default.

Encapsulation – hiding implemantation behind public interfaces, reducing coupling increases plug-ability / reusability, maintainability etc.

private fields have two purposes:

1 – reference to object or variable that used for internal implementation of class

2 – hold the state of an object , backing field for public property.

The shortcut in Visual Studio:
propful [tab] [tab]

private int myField;
property int MyProperty{

  get{return myField;}
  set{
    if(value > 100)
      myField = value;
    else
      //tell the caller that they can not do this
  }
}

Full property definition and private fields to control access to private fields  / state of an object.

propg [tab] [tab]

public int MyProperty{ get; private set;}

Restricts setting of property to just the class internal implementation

More on this topic could be found on microsoft.com

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.