cookieChoices = {};

Friday 29 November 2013

OOPS


Overview

 What is an Object?
 What is not an Object?
What is state of an Object?
What is the Lifecycle of an Object?
How will you distinguish two Objects?
What is the relationship between Class and Object?
Define Application using Objects?
 Principles of Object Orientation
Encapsulation
Inheritance
Polymorphism
Encapsulation is binding of State and Behavior together
 Inheritance is based on “is a” relationship.
Understanding Polymorphism with Examples.


 Class: A class is a template / skeleton / blueprint for creating an object.

 Object: An Object is an entity that has properties for validations, methods for functionality and events for depicting the change of state.

 Every object has the data and behavior with which they are differed. Data associated at any given instance of time is the state of an object.

Component: A ready to use third party object can be called as a Component. It can be replaced without any changes in the application. A component is generally used by a programmer as an object.

An application can be called as a collection of related objects exchanging messages with each other.

 Loosely coupled objects are better than tightly coupled objects i.e. the lesser the information given to other objects the better it is as the objects are loosely coupled the dependencies are less and stronger security.

Every object oriented language should have three features
·         Encapsulation
·         Inheritance
·         Polymorphism


 Encapsulation: Binding of data and behavior i.e. functionality of an object within a secured and controlled environment is encapsulation.
 Inheritance: The Process of acquiring the existing functionality of the parent and with new added features and functionality by a child object is called inheritance. The advantages of inheritance are Generalization, Extensibility and Reusability. For example: A calculator is a generalized form of mathematical operations where as a Scientific calculator is an Extended and Specific form.
 Polymorphism: An object in different forms and in each form it exhibits the same functionality but implemented in different ways. For example: A man who knows more than one language can speak any language he knows. Here the functionality is speech and person is the object. A faculty can take a form of Java Faculty or MSNET faculty and in both the forms he teaches, but what he teaches differs. Here functionality is teach and faculty is the object.
Object Creation and Instantiation In MS.NET when an object is created there is no way to get the address of an object. Only the reference to the object is given through which we can access the members of the class for a given object. When an object is created all the variables (value/ reference types) are allocated the memory in heap as a single unit and default values are set to them based on their data types.

Agenda:
1. Write a class and add field members to the class
2. Create an Object of the Class and understand the difference between object and reference.
3. Access the members of the object
4. Copy the reference in another reference variable.
5. Abandoning the object.
6. Working with Methods
7. Working with Properties
8. Constructor & Destructor.
9. Working with “static” Members

Working with Classes & Objects:
Account Example
Step 1: Create a new project (File à New Project). Name: AccountApplication, Project Type: C#, Template: Windows Application
Step 2: View à Solution Explorer, Right Click on Project à Add à Class and name it as Account
Step 3: Add to class the following code.
Code in C#:
class Account
{
public int Id;
public String Name;
public Decimal Balance;
 public Account()
 {
MessageBox.Show(“Object Created”);
 }
~Account()
{
 MessageBox.Show(“Object Destroyed”);
 }
}
Explanation: Account a; “a” is a refrence variable of type Account. Note: “a” is not an object of type Account. a = new Account();
Creates an object of type Account (allocating memory on heap to every member of the Account class) and its reference is assigned to „a‟.
Every member allocated memory is set to its default value based on the datatype.
The value of the reference variable is reference to an object on heap.

Account a; 'Declaration a1 = new Account(); 'Initialization

Step 4: In the AccountApplication, Change the name of the Form, “Form1” to “AccountForm” and design the following GUI
Step 5: For every control on the form set Text and Name properties.
Step 6: In DesignView, doubleclick on every button to generate event handlers in Code View of the Form
a.Id = 1; The above statement can be read as: “Id” menber of an object of type Account referenced by “a” is set to 1.
Note: If a reference variable is not intialized i.e referring to null, then trying to access any member using it will throw a runtime exception i.e. “NullReferenceException”.

Account a1; a1 = a //Copies the value of a (reference to the object) into a1 and thus both “a1” and “a” refers to the same object.

Note: One Object can have many references but one reference variable cannot refer to many objects.


Step 7: Add the following code to the AccountForm i.e Handle all the buttons Click event (Double click on button in design view)
Account Form Code in C#:
public partial class AccountForm: Form
 {
     Account a;
    private void btnCreate_Click(...)
    {
          a = new Account();
     }
private void btnGet_Click(...)
{
 txtId.Text = a.Id.ToString();
txtName.Text = a.Name;
txtBalance.Text = a.Balance.ToString();
}
private void btnClear_Click(...)
{
 txtId.Text = "";
txtName.Text = "";
 txtBalance.Text = "";
}
private void btnSet_Click(...)
{
a.Id = int.Parse(txtId.Text);
a.Name = txtName.Text;
 a.Balance = double.Parse(txtBalance.Text);
}
private void btnDestroy_Click(...)
 {
a = null;
}



private void btnClear_Click(...)
{
 txtId.Text = "";
txtName.Text = "";
 txtBalance.Text = "";
}
private void btnSet_Click(...)
{
a.Id = int.Parse(txtId.Text);
a.Name = txtName.Text;
a.Balance = double.Parse(txtBalance.Text);
}
private void btnDestroy_Click(...)
{
a = null;
}

private void btnGC_Click(...)
{
GC.Collect();
 }
private void btntemp_Click(...)
 {
 Account a1 = new Account();
a = a1;
}
private void btnGetGeneration_Click(...)
 {
 MessageBox.Show(GC.GetGeneration(a).ToString());
 }
}


Working with Methods
The methods of the object are used to describe the functionality / behavior.

 Notes:
1. An instance method of a class is always invoked using a reference to an object.
2. While writing a method in a class do not set to it any data as parameter or return type, anything which is already the data member in the same class.
3. In a method “ “this”(CS) is reference to the current object on which the method is invoked.
4. If parameter/local variable and data member of a class have same name, the local variable takes the precedence over data member and if data member has to accessed in such a method then “this” (CS) can be used.
5. The class should be always programmed in such a way that, it‟s not specific to any particular type of application so that the same class can reused in different applications / environment. For example, don‟t use in class functionality like MsgBox or Console.WriteLine or Button or Label or TextBox etc….
6. Whenever any of the business rules of an object or the integrity of the property or a method is violated, it should respond by throwing a runtime exception. For example in the above method Withdraw( ) we are checking for balance to be a minimum of 500, if violated an exception is raised.

Recommendation: A method name should start with uppercase and parameters should use camel notation. Step 8: In the Account Class add the following deposit and withdraw method.

public void Deposit(decimal amount)
{ this.Balance += amount }
public void Withdraw(decimal amount
{
if (this.Balance - amount < 500)
throw new ApplicationException("Insufficient Balance");
else
this.Balance -= amount
}
Step 9: Add Deposit (btnDeposit) and Withdraw (btnWithdraw) buttons and Amount (txtAmount) textbox to the AccountForm. Add the following code to the event handler of the btnDeposit and btnWithdraw.

pivate void btnDeposit_Click( . . . )
 { a.Deposit(decimal.Parse(txtAmount.Text)); }

private void btnWithraw_Click( . . . )
{ a.Withdraw(decimal.Parse(txtAmount.Text)); }








Working with Object Properties



1. A Property encapsulates a field member of the same class, so that the field member is not freely accessible outside the class and the required validation/restriction can be put over it.
2. A property is made of two blocks i.e. Get and Set. Get block is invoked when the property is used on RHS and Set block is invoked when the property is used on LHS.
3. A property procedure doesn‟t hold any data by itself instead it depends on some private field member of the class.
4. A Set block can validate the “Value” before it is assigned to the field member of the class being encapsulated by the property. Similarly the field member can be validated before its value is returned in the Get block.
5. Using a property the field member can be restricted with either “ReadOnly” or “WriteOnly” access.
6. A class which has all its field members as Private and if required restricted access to these members is given using Public Properties is called “Fully Encapsulated Class”.

Syntax in C#:
Private <Datatype> _<propertyname>; public <Datatype> <PropertyName>
 {
[private]
get { return _<propertyname>; } [private]
set { _<propertyname> = value; }
 }
                                                                             
Step 10: Add the properties for Name, Balance and Id with following conditions:
Balance should be ReadOnly.
Name should accept greater or equal to and 5 characters and less than or equal to 20 characters only
Id should be set only once.

Edit the code in the Account Class as below.
private int _Id
private string _Name
private decimal _Balance
public decimal Balance
{
get { return _Balance; }
}
public String _Name
{
get { return _Name; }
 set { if (value.Length > 8)
throw new ApplicationException("Name cannot be > 8 characters"); _Name = value; }
 }

private bool idAlreadySet;
public int Id
{
get { return _Id; } set { if (idAlreadySet) throw new ApplicationException("Id is already set"); _id = value; idAlreadySet = true; }
 }
Step 11: In btnSet_Click of AccountForm please replace a.Balance = Decimal.Parse(txtBalance.text) with a.Deposit(decimal.Parse(txtBalance.Text))
Constructors and Destructors

A constructor is a member method of a class which is automatically executed / called as soon as the object of that class is created and thus it is ideally used for initializing the field members of the object.
1. A constructor has same name as the class and doesn‟t have a return type not even void.
2. A constructor without a parameter is called default constructor and the one with parameters is called as Parameterized constructor.
3. If a class doesn’t have any form of constructor, a public default constructor is automatically added to it by the language compiler.
4. Copy Constructor is used to create a new object by duplicating the state of an existing object and this is done by copying the data members of existing object in new object data members.

Syntax in C#:
<Class name>()
{ //default constructor }
 <Class name>(<datatype> p1, …) { //parameterized constructor }
 <Class name>(<Class Name> <parname>) : this(. . .) { //copy constructor }
                                                            
Step 12: Add the Following code to the Account Class
public Account()
{ }
 public Account(int id, String name, decimal balance) : this()
 { this.Id = id; this.Name = name; this._Balance = balance; }

public Account(Account a) : this(a.Id,a.Name,a.Balance)
 { //this.Id = a.Id; //this.Name = a.Name; //this._Balance = a.Balance; }
 Step 13: In AccountForm make the following Changes:
 private void btnCreate_Click(. . .) Handles btnCreate.Click
 {
int id = int.Parse(txtId.Text);
string name = txtName.Text;
decimal initialBalance = decimal.Parse(txtBalance.Text);
 a = New Account(id,name, initialBalance);
}
Note: Once the above code is changed in AccountForm, btnSet_Click is no more useful and thus it can be removed

Destructor
A destructor is used to release the resources that an object is holding. When an object is ready to be destroyed Finalize method / Destructor is called on that object.
In C++, destructor of a class is responsible for destroying all the other objects which the object of this class has created during its lifetime. (In C++ we don‟t have Garbage collector)
In .NET, all the dependent objects are automatically ready for Garbage Collection when the main object doesn‟t have any references thus the destructor here doesn‟t have same significance as in C++.

Syntax in C#: Note: A destructor in C# cannot have any access modifiers ~<class name>() { }.
Because its not predictable when the Destructor method is going to be executed, its not recommended to only rely on destructor for releasing of resources and thus Microsoft has suggested two methods that can be invoked by the programmer for the release of resources i.e. Close() or Dispose().
Working with “static” Members
For every new instance of a class all the instance members are allocated memory, but static field members of a class are allocated memory only once irrespective of the number of objects created and they are allocated memory when the class is loaded. These members are also called class members and are accessed outside the class using class name.

Note: A class is loaded when either the static members of the class is accessed for the first time or when the first instance of the class is created. A class once loaded will remain in memory permanently and thus also are all static members of that class.

Note: A public static member of a class can be used as Global member of the application because it can be assessed using class name from any part of the application.

Static Constructor: A constructor is defined with the keyword as static (in C#). It is used to initialize the static member dynamically and is executed when the class is loaded.

This is invoked by the CLR when the class is loaded by it and hence cannot be overloaded nor can be declared with any accesses specifier like public or private.

 Series of events that occur when the first object is created:

1. Class is loaded.
2. Static members are loaded and allocated memory.
3. Static constructor is executed.
4. Instance members are loaded and allocated memory.
5. Instance constructor is executed.

Note: Static Constructor cannot access Instance members of the class. This is because when the static constructor is executed the instance members are not allocated any memory.


Code in C#:

 Step 14:
 public static int MinBalance = 500;
 Step 17:
 public static int _PrevId
private int Id;
Step 18: public Account()
{ _PrevId += 1; _Id = _PrevId; }
 Step 19: Id is now changed to ReadOnly Property
public int Id { get { return _Id } }

Step 15: In Withdraw method replace the constant value 500 with the static member "MinBalance"
Step 16: In Form: Add btnGetMB and btnSetMB buttons and txtMB textbox with the following code.



private void btnGetMB_Click(...) { txtMB.Text = Account.MinBalance.ToString(); }
Private Sub btnSetMB_Click(...) { Account.MinBalance = Decimal.Parse(txtMB.Text); }

Step 20: Because “Id” is now auto increment field, remove the id parameter from the constructor of Account Class
Step 21: Remove “id” argument while creating the Account object in btnCreate_Click of AccountForm        
Static Methods: A method which does not have anything to do with the state of the object can be marked as static method.
Eg: class File {
public static void Copy(string srcPath,string destPath) { . . . }
 }
Note: All methods and properties (procedures) of the class irrespective of whether they are static or not are allocated memory only once.

1. Outside the class a static members of a class can be accessed using class name where as the instance member of a class must be accessed using a reference variable referring to an object of that class.
2. Instance members of the class cannot be accessed in a static constructor or any other static method or property of the class (unless it is qualified by a reference variable referring to an object of that class).

For Example
 public static void Foo()
{
//_Balance = 100; // Is Invalid
Accout a = new Account();
a._Balance = 100; // IsValid because _Balance is qualified by “a” which is reference to an object.
}

3. An instance member can access static members of the class.
4. “this” cannot be used in the static member of a class.
5. A class in C# can be declared as static and such a class can have only static members and instance members are not allowed. Also such a class cannot be instantiated.


static class Demo { public static int P1; public static void Foo() { } }

C Sharp Language Basics

Integral Types

DataType
Size
.Net(CTS)
Comments
byte
1
System.Byte
0 - 255 It is Unsigned
sbyte
1
System.SByte
-128 to 127 - Signed
short
2
System.Int16

ushort
2
System.UInt16

int
4
System.Int32

uint
4
System.UInt32

long
8
System.Int64

ulong
8
System.UInt64



 Floating Types
float
4
System.Single
Has up to 8 digits after decimal
double
8
System.Double
Has up to 16 digits after decimal




Deciaml
16
System.Decimal
Has fixed 28 digits after decimal and its fixed


 Other DataTypes
string *
4
Systring.String
Uses Unicode Charset
char
2
Systring.Char
Uses Unicode Charset
bool
1
Systring.Bool

object *

System.Object
Generic Datatype


 Variable Declaration Syntax:
int a,b;
 int a=10, b=20;
·         A local variable declared must be explicitly initialized before used in an expression otherwise gives an compilation error


 using System;
class Program
{
public static void Main()
 {
int n = 256;
 byte b;
unchecked //Overflow checks are not done…
 {
b = (byte) n;
 Console.WriteLine(b);
}
checked //Overflow checks are done…
 {
b = (byte) n;
Console.WriteLine(b);
 }
 double dbl = 0.6D;
//0.6 float f = 0.6F;
decimal dec = 0.6M;
//float and decimal requires casting dec = 10;
 //Integer to decimal //f = dec;
//Invalid //Valid in VB //dec = f;
 //Invalid f = (float) dec;
//In VB-Implicit dec = (decimal) f;
//“decimal” should be explicitly casted to every other type if required.
 string s = "Demo";
char c = 'S';
//In VB - "S"c
 //int to char. n = c;
//In VB: n = AscW(c)
 /*c = n; invalid */

 c = (char) n;
//In VB: c = ChrW(n)
//bool – int /anydatatype explicit or implicit casting is not allowed either direction
//string to int s = "100";
 n = (int) s;
//Invalid – String cannot be casted n = int.Parse(s);
//if failes throws, FormatException bool bln = int.TryParse(s, out n);
//n = (int) s; //Invalid //int to string s = n.ToString();
//s = (string) n //Invalid
//long to float - Same as VB
long lng = 10L;
f = lng;
//because range of long is smaller than float
 lng = (long) f;
object obj = n; //Boxing
n = (int) obj; //Unboxing

 var n = 0
// n is of type
int var s = "Hello"
// s is of type string
const double PI = 3.14;
byte b1, b2, b3;
 b1 = b2 = 10;
//In VB it is not valid b1 = b2 + b3;
//Compilation Error
//if byte, short or char variables are used in an expression they are automatically raised to the rank of int.
 b1 = (byte) (b2 + b3);
Console.WriteLine(3 / 2); //Result - 1
                Console.WriteLine(3.0 / 2); //Result - 1.5
n = 10;
int m = n++;
//m=n; n=n+1 - Post Increment
Console.WriteLine(n + " " + m);
m = ++n; //n=n+1; m=n - Pre Increment
Console.WriteLine(n + " " + m);
//?: Conditional Operator (VB: IIf)
int max;
max = n > m ? n : m; //?: Operator
           //Enum Sample
n = 2; //n is int
WeekDay wd = WeekDay.Sat;
wd = (WeekDay) n;
                //Explicit
                //n = wd;
                //Invalid n = (int) wd;
//Explicit - In VB.NET it‟s not required
 }
 }
enum WeekDay : int //WeekDay is subtype of int
 {
Sun=1, Mon, Tues, Wed=5, Thus, Fri, Sat
 }

Enum can be subtype of any integral type only

OverflowException.

Operators Arithmetic
+, -, * , / , % (mod) (Power operator is missing)
Logical Operators
^ (XOR), !(NOT) && (VB-AndAlso) , || (VB-OrElse)
Ternary Operator
?:
String concatenation
+ (VB-&)
Increment, decrement
++ , --
Bitwise
<< , >>, & , | , ~ (complement/negation)
Relational
= = , != , < , > , <= , >=
Assignment
= , += , -= , *= , /= , %= , &= , | = , ^= , <<= , >>=
Type information
is , sizeof , typeof, as
Indirection and Address
* , -> , [] , &

Note for VB.NET Programmers:

In C# the arithmetic operator „/ ‟ is the same for both floating point and integer datatypes and the result depends on the operands.

Control Statements
if-statement: if (BooleanExpression) { statement; } else if (Boolean-Expression) { statement; } else { statement; }
Switch Statement int expr; switch (expr) //expr can only integral type / char / string { case 0: //value of case must be a constant. statements; goto default; // or break can be used. case 1: case 2: statements; break; //break must be preset after every case with statements default: statements; break; //break must be present after default also. }
while…..loop while (BooleanExpression) { Statements; }
do { Statements; }while (BooleanExpression);



for and foreach statements

for ( initializer; condition; iterator )
{
statements;
}

foreach (DataType identifier in <Array or Collection>) {
embedded-statements;
}

 for (int i = 0; i < 10; i++)
 {
if (i == 7) break;
 if (i == 3) continue;
 Console.WriteLine(i);
}

 foreach (string s in args)
Console.WriteLine(s);
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (i == j) break;
Console.WriteLine(i + " " + j);
}
}
}
}

·         “break” and “continue” statements can be used in “for” and “while” loops.
·         C# doesn‟t support “With” statement

Working with Arrays
1.       Single-Dimensional Arrays
int [] myArray = new int [5];
string []myStringArray = new string[5];
 When you initialize an array upon declaration, it is possible to use the following shortcuts:
 int[] myArray = {1, 3, 5, 7, 9};
string[] weekDays = {"Sun", "Sat", "Mon", "Tue"};
It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable.
For example: int[] myArray;
 myArray = new int[] {1, 3, 5, 7, 9}; // OK
 myArray = {1, 3, 5, 7, 9}; // Error
 weekdays = new string[] {“Sunday”, “Monday”, “Tuesday”};
2. Multidimensional Arrays
int[,] myArray = new int[4,2];
Also, the following declaration creates an array of three dimensions, 4, 2, and 3:
int[,,] myArray = new int [4,2,3];
You can initialize the array upon declaration as shown in the following example:
 int[,] myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};
You can also initialize the array without specifying the rank:
 int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};
 If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. For example:
int[,] myArray; myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}}; // OK
 myArray = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error
class Program
 {
static void Main(string[] args)
{
 int[] ar = new int[ ] {1,2,3,4};
 Console.WriteLine(ar.Length);
Console.WriteLine(ar.Rank); //Prints Number of Dimensions in array.
 foreach (int n in ar)
Console.WriteLine(n); //To increase the size of existing array and also retaining data in it. i.e equivalent of Redim Preserve in VB.
 int[] temp =ar;
ar = new int[temp.Length +1];
 Array.Copy(temp, ar, temp.Length);
temp=null;
foreach (int n in ar)
Console.WriteLine(n);
}
 }








 Working with Methods
using System;
 class Program2
{
public static void Main()
 {
 int res = Add(10, 2);
 int[] mar = { 1, 2, 3, 4 };
 res = Add(mar);
res = Add();
 res = Add(1, 2, 3, 4, 5);
 res = Add(1, 2, 3, 4, 5, 6);
 res = Add(1, 2, 3, 4, 5, 6, 7); //Pass by value or reference example…. int n1, n2, n3; n1 = n3 = 10;
Foo(n1, out n2, ref n3); Console.WriteLine(n1 + " " + n2 + " " + n3); }
 //Pass by value and reference example static void Foo(int a, out int b, ref int c)
{
 a++; b = 20; c++;
 }
static int Add(int a, int b)
 {
return Add(a, b, 0);
}
static int Add(int a, int b, int c)
{
return a + b + c;
}
static string Add(string s1, string s2)
{
return s1 + s2;
}
static int Add(params int[] ar)
{
int sum = 0;
foreach (int n in ar)
sum += n; return sum;
}
}


·         Out parameter must be initialized in the method and are generally used in situations where we want to return more than one value from the method.
·         C# doesn’t support Optional parameters with default values and Named arguments.

static int Foo(int a) { if (a != 0) return a; }

If a method has return type anything other than “void”, all code paths in it must return a value.
The example gives compilation error because if a==0 nothing is mentioned as return value.



General Points; For String: @"C:\Demo" or "C:\\Demo", "This is \"Quoted\" String"