Tuesday, January 26, 2016

Lesson 3

Outline


Chapter 10

Properties
     Full
     Private Fields
     Auto-Implemented
     Read Only
     Write Only
     Calculated

Properties

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Properties are used in classes to enable the derived objects to hold values (even different values) within the object. Properties generally are associated with a private field variable that is not accessible outside the class/object. The property provides a method to set or get the value of the private field from outside the object.

It is important to think of properties as adjectives or descriptors of the object. Suppose we had a person class. Some properties might be used to describe the object (class instance)  such as name, height, weight, race, or gender. The person class containing these properties allow the object to maintain its own unique description. So a person object for me might have different values for each of the properties even though they are based on the same class.

Full Property

Full properties allow the greatest flexibility for a developer. All of the parts of the property are exposed and can be modified to create the desired behavior. Below we have a simple person class with a single property Name.

class Person
{
 
    private string name;

     public string Name
     {    
     get { return name; }
     set { name = value; }
     }  
}
 


Examining the property we see that part of the property is public and part is private. The public Name is what the developer will see when the property is accessed from an object. The private name will hold the value set by developer.
Person me = new Person();
me.Name = "Larry Taylor";

In the code above we first create an instance of the Person class, in this case our object will be named me. (Note: me is a horrible object name, please try to use a descriptive name for your instance). Once me is instantiated we can then access the properties defined in the class via the newly created object. me.Name is accessing the public Name property we defined in the class allowing me to set the value of the private name variable to "Larry Taylor"
When a value is applied to a property it accesses the properties "set" statement. In our name property we defined we have this statement: set { name = value; } When value the is applied the property sets the private field "name" equal to the value being passed into the property.
The reverse is true as well. When the get accessor is called the value stored in the private field is returned.

Console.WriteLine(me.Name);

Name refers to the property and within the property the private field value is returned.

Auto-Implemented

Sometimes (well most of the time) your class will only need simple properties. C# has a shortcut for creating simple properties call auto-implemented properties. These properties work EXACTLY like the full properties above have a lot of the plumbing hidden from the developer. The Name property we created above using the full property approach would be written as follows using auto-implemented:
       
public string Name { get; set; }

We still have a get and set to apply and retrieve the value held in the private field. But where is the private field? It is still there only hidden. This approach makes for a much simpler property to generate within the class. The shortcut for the auto-implemented property is prop followed by two tabs.

Read Only Properties

Read only properties cannot have the private value set outside of the class. We can still read it from outside the class but not change it. Think about a class for account management at a bank. We might want to set the account number once from within the class and then all the methods within the class access the account number during the debit and credit functions of the account management process. We would not want the account number to be changed mid process when making a deposit.

Read Only Full Property

     private string name;

     public string Name
     {    
     get { return name; }
     } 

Note: The set accessor is no longer present.

Read Only Auto-Implemented Property

public string Name { get; private set; }

The set accessor is marked private to prevent access from outside the class

The value of the property can only be set within the constructor when we instantiate a class into an object or within a method located in the same class. 

Write Only Property

These are properties that can be set outside the class but not read from outside the class. This type of property is not used that often. Examples are below:

Read Only Full Property

     private string name;

     public string Name
     {    
     set { name = value; }
     }  
 
Read Only Auto-Implemented Property

public string Name { private get; set; }

Properties are a useful way to enable your class/object to hold data specific to that instance of the object.

Calculated Properties

This type of property "assembles" or generates the return value of the property dynamically when the get accessor is called.

public string FirstName { get; set; }
public string LastName { get; set; }

public string FullName
{get { return FirstName + ' ' + LastName; }
} 
Our example above contains 3 properties. Two of the properties allow the developer to read and write the first and last name. The third property is a read only property that assembles the first and last name property values into a full name property. Since we have the first and last name there is no need to create a property to accept a full name. We just use the values we already have in the class.

Properties are an essential component of object oriented programming. They allow our objects to retain values specific to its instance and allow for proper encapsulation of information.


Friday, January 15, 2016

Lesson 2

Outline


Chapter 10
  • Constructors
    • Default/Parameterless
    • Overloaded Constructors
  • Destructors
  • Static Class Members
  • Read Only Instance Field
Constructors

We introduced the concept of a class constructor last week. We will expand on it this week using overloaded constructors. A class can support one to many constructors in a class. It must follow these rules:

All constructors must have the same name as the class.
All constructors must have a different combination of parameter types.


namespace Chapter10_HousePlans_Sample
{
    /// <summary>
    /// Simple house plans class
    /// </summary>
    class HousePlans
    {
        /// <summary>
        /// Private (not visible outside of class) variable to keep track of door status (defaults to false:closed)
        /// </summary>
        private bool doorOpened;
        private int bedrooms;
        private int bathrooms;
 
        /// <summary>
        /// Public (visible outside the class and even the project) method to change to the door open status to true:opened
        /// </summary>
        public void OpenDoor()
        {
            doorOpened = true;
        }
 
        public HousePlans()
        { 
        }
 
        public HousePlans(int bedrooms)
        {
            this.bedrooms = bedrooms;
        }
 
        public HousePlans(int bedrooms, int bathrooms)
        {
            this.bedrooms = bedrooms;
            this.bathrooms = bathrooms;
        }
 
        /// <summary>
        /// Public (visible outside the class and even the project) method to change to the door open status to false:closed
        /// </summary>
        public void CloseDoor()
        {
            doorOpened = false;
        }
 
        /// <summary>
        /// Overrides the standard tostring method (available in all object) to a specific string
        /// </summary>
        /// <returns>Status of the door(open or closed)</returns>
        public override string ToString()
        {
            return "The door is " + (doorOpened ? "Open" : "Closed");
        }
    }
}

In our sample class above we have three constructors, a parameterless constructor, a constructor that takes one integer, and a constructor that takes two integers. Note each constructor takes a different number of parameters. We could also differentiate constructors by the type of parameter as well.

public HousePlans(int bedrooms)
{
    this.bedrooms = bedrooms;
}
 
public HousePlans(string paintColor)
{
    this.paintColor = paintColor;
}

If we had two constructors in our class that each took a single parameter as in our example above, there would be no conflict. Even though the constructors are identical in the number of parameters they still differ by type. One constructor takes an integer parameter and the other takes a string. Also, once we add our own constructor the hidden default constructor is removed. If we still want a parameterless constructor in our class we will need to manually define it.

NOTE: THE PARAMETER NAMES NOT CONSIDERED WHEN OVERLOADING A CONSTRUCTOR. ONLY THE NUMBER OF PARAMETERS AND THIER TYPES.

Destructors

A constructor creates an instance of an object based on a class. A destructor destroys the created object allowing the system garbage collection to free up any resources used by the object. Without destructors the application could grow in memory taking up more and more resources. This is called a resource or memory leak.

To implement a destructor in our class we implement the IDisposable interface within our class. Implementing an interface in a class will cause the class to stub out code necessary to support the interface functionality.

Adding the IDisposable interface to our HousePlans class:
class HousePlansIDisposable

To add the interface to our class, we add a colon to the right of the class name. After the interface is added it must be implemented (supported) within the class. To implement the IDisposable interface click on the word "IDisposable" and a small underscore will appear.








After the underscore appears, hover the cursor over it to enable a small drop down.












When the menu appears, click the "Implement interface IDisposable". Viewing the code of the class you will notice a new method "Dispose"


public void Dispose()
{
    throw new NotImplementedException();
}


Remove the "throw new NotImplementedException():". Once implemented, you can "dispose" of your object like this:


//Creates an instance of the class
HousePlans myHouse = new HousePlans();
//Disposes or removes the instance of the class
myHouse.Dispose();


It is a good idea to implement the IDisposable interface even though we are not doing anything within the dispose method. It does provide a nice way to remove any unused objects as well as a place holder when we do need to perform some tasks when disposing of an object. We will discuss that in a later lesson.


Static Class Members


A static class is basically the same as a non-static class, but with one difference. A static class cannot be instantiated. That is, we cannot create an instance of a static class (i.e. use the new keyword). Static classes are generally used to hold to hold methods that do not rely on an instance value.


You may recall in the previous lesson creating the myHouse and yourHouse objects. While based on the same class they may still contain different attribute values. These differences are based on the instance of the object. A static class does not use any instance settings and therefore does not require the new keyword.


public static class TemperatureConverter
{
    public static double CelsiusToFahrenheit(string temperatureCelsius)
    {
        // Convert argument to double for calculations. 
        double celsius = Double.Parse(temperatureCelsius);
 
        // Convert Celsius to Fahrenheit. 
        double fahrenheit = (celsius * 9 / 5) + 32;
 
        return fahrenheit;
    }
 
    public static double FahrenheitToCelsius(string temperatureFahrenheit)
    {
        // Convert argument to double for calculations. 
        double fahrenheit = Double.Parse(temperatureFahrenheit);
 
        // Convert Fahrenheit to Celsius. 
        double celsius = (fahrenheit - 32) * 5 / 9;
 
        return celsius;
    }
}


This class has the same look and feel of the HousePlans class with one exception. Notice the keyword "static", this denotes that the class does require an instance to access the methods. To use the HousePlans methods we had to create an instance of the HousePlans class.


//Creates an instance of the class
HousePlans myHouse = new HousePlans();
//Access method within the new instance
myHouse.CloseDoor();
//Disposes or removes the instance of the class
myHouse.Dispose();


To access a method within a static class we only need to call the method directly.


//Static classes/methods do not require an instance to be accessed
TemperatureConverter.CelsiusToFahrenheit("32");


When a class is going to work EXACTLY the same consider making the class a static class.


Read Only Instance Field


Read only fields within a class can only have a value applied where the instance is defined or within a constructor.


//Read only field with value applied
public readonly string Address = "123 Main";
 
 
//Constructor that sets value of read only field
public HousePlans(int bedrooms, string address)
{
    this.bedrooms = bedrooms;
    this.Address = address;
}

Once the instance of a class is created, this value cannot be changed. The value of the field can be accessed from an instance of the class.

//Create instance of the HousePlans class.
HousePlans yourHouse = new HousePlans(3, "1000 Capitol");
//Access the read only field
Console.WriteLine(yourHouse.Address);


Attempting to set a value at the instance level will cause an exception.
















Read only fields are used when the value can change from one instance of a class to another but once instaniated the cannot change for the life of the object.

Thursday, January 14, 2016

Lesson 1

Outline
 
Chapter 10
  • Class
  • Object
  • Encapsulation
  • Constructors
 
 Example: HousePlans Class
 
Class Framework
 
A fundamental concept in object oriented programming languages, like C#, is the class. A class is a template or plan for an object. What's an object? It is a representation of thing based on a class. A class is to an object as house plans are to a house.


Lets create a simple class called HousePlans


namespace Chapter10_HousePlans_Sample
{
    /// <summary>
    /// Simple house plans class
    /// </summary>
    class HousePlans
    {
        /// <summary>
        /// Private (not visible outside of class) variable to keep track of door status (defaults to false:closed)
        /// </summary>
        private bool doorOpened;
 
        /// <summary>
        /// Public (visible outside the class and even the project) method to change to the door open status to true:opened
        /// </summary>
        public void OpenDoor()
        {
            doorOpened = true;
        }
 
        /// <summary>
        /// Public (visible outside the class and even the project) method to change to the door open status to false:closed
        /// </summary>
        public void CloseDoor()
        {
            doorOpened = false;
        }
 
        /// <summary>
        /// Overrides the standard tostring method (available in all object) to a specific string
        /// </summary>
        /// <returns>Status of the door(open or closed)</returns>
        public override string ToString()
        {
            return "The door is " + (doorOpened? "Open""Closed");
        }
    }
}



The above class defines our houseplans class. It contains 1 private variable doorOpened which will keep up with the status of the door whether it is opened or closed. Note: it is standard practice to name variables using camel casing. Using camel casing the first word is lower case and the first letter of each remaining word in capitalized. i.e. whiteHouse, incomeTaxStatement, etc.



Objects


When a object is created from a class it is said to be instantiated. An object based on the class (or instance) is created using the new statement.
HousePlans myHouse = new HousePlans();
 When a object is created from a class it is said to be instantiated. An object based on the class (or instance) is created using the new statement.



Creating multiple objects (instances) of a class. If we create two or more objects based on the same class there are not considered equal or the same. They will work identically but can contain different property values.




HousePlans myHouse = new HousePlans();

HousePlans yourHouse = new HousePlans();


Even though our houses are built using the same plans, yourHouse and myHouse are independent of each other. When I can call the myHouse.OpenDoor() method to open the door, nothing in yourHouse is affected.

Encapsulation

Encapsulation, in the context of C#, refers to an object's ability to hide data and behavior that are not necessary to its user. Encapsulation enables a group of properties, methods and other members to be considered a single unit or object.

 The following are the benefits of encapsulation:
  • Protection of data from accidental corruption
  • Specification of the accessibility of each of the members of a class to the code outside the class
  • Flexibility and extensibility of the code and reduction in complexity
  • Lower coupling between objects and hence improvement in code maintainability
Encapsulation is used to restrict access to the members of a class so as to prevent the user of a given class from manipulating objects in ways that are not intended by the designer. While encapsulation hides the internal implementation of the functionalities of class without affecting the overall functioning of the system, it allows the class to service a request for functionality and add or modify its internal structure (data or methods) to suit changing requirements.
We use terms like "scope" when defining an accessibility level.

Public - Accessible from anywhere in the application and outside the application
Internal - Accessible from within the application only
Private - Only accessible to its peers and subordinate methods and properties

Constructors

When an object is created from a class the class constructor is called. All classes have at least one constructor. The default constructor for a class is hidden but can be overridden.  In our class above the constructor is hidden. If it was visible it would look like this:

public HousePlans()
  { 
  }

A constructor is always named the same name as the class and can take 0 or more parameters.

When we instantiate a new object from a class we utilize the constructor of the class.

HousePlans yourHouse = new HousePlans();

The code right of the new command matches our default constructor. It uses the name of the class and takes zero parameters.

Feel free to comment below any questions or thoughts.