Professional Documents
Culture Documents
CSharp
CSharp
Course Objectives
To understand .NET technology and .NET framework To gain ability to work in Visual Studio 2008 Team System IDE To recap Object Oriented Concept and its use in C# To gain ability to work with windows programming and event handling Usage of built-in testing and code analysis tools in Visual Studio 2008 Team System in .NET framework
Course Pre-requisites
Fundamental programming skills C as a programming language Object Oriented Programming Concepts
Why .NET?
Need to create a new project re using Marketing Module of ABB Project developed in VB.Net Inventory Module of XYZ Project developed using Java Sales Module of EZEE Project developed using C++
Applications developed in different languages. Incorporating them in a single project will be a NIGHTMARE!
6
Why .NET?
A nightmare? Not anymore. Microsoft .NET is a simple solution to this seemingly nightmarish situation. Equipped with various new features, it provides you with interoperability
Interoperability
Components of applications written in one programming language can be used for applications developed in other programming languages
Browsing Era
GUI Era
Negatives of Internet Browsing Era: Read-only No user control Too many islands Keyboard only
8
Before COM, applications were completely separate entities with little or no integration
COM provides a way for components to integrate; However, each component must provide the plumbing and objects cannot directly interact
10
With the .NET Framework common language runtime (CLR), components are built on a common substrate; No plumbing is needed and objects can directly interact
11
Hence Microsoft .NET Framework a computing platform for developing distributed applications for the Internet.
12
.NET
What is .NET? The set of Microsoft software technologies Connecting the world of information, systems, people and devices. Small applications communicating with other applications
Located on the same machine or Via the Internet.
What is .NET Framework? A new computing platform Simplifies application development in the highly distributed environment of Internet
13
Features of .NET
Single programming model Integrity with COM
Distributed Systems
Easy Deployment
15
Managed code
Assembly IL Code
16
Start
OS
Compiler
EXE/DLL (IL)
Policy
Class Libraries (IL)
IS Permissions?
Class Loader
Target Machine
Security Exception
Y Is Type Safe ?
Y N Is PreJIT ? JIT N Type Safe Exception
JIT Compiler
Security Check
Execution
Y Execution
17
Features of CLR
Automatic Memory Management
Provides garbage collection
Language Interoperability
Platform Independence
Security Management
Provides Code Access Security (CAS) Type Safety
18
Assemblies
Assemblies are fundamental building blocks of a .NET Framework application. They contain the types and resources that make up an application One Assembly can contain one or more files. When you compile your source code, by default the exe/dll generated is actually an assembly An assembly consists of four internal parts: Assembly Manifest or Metadata Type Metadata IL code Resource files
21
What is a Class ?
A Class
Is a blue print used to create objects. Is a software template that defines the methods and variables to be included in a particular kind of Object.
Examples :
Employee, SoftwareEngineer, TechnicalEvangelist, Payroll
24
What is an Object ?
An object
Is a unique, identifiable, self-contained entity that contains attributes and behaviors.
25
Features of C#
Object-oriented Simpler language
Compared to earlier OO languages like C++, it is simple Designed considering the pitfalls of earlier languages
27
Structure of a C# Program
Structure of a C# program
using System; class FirstProgram
{
public static void Main() { Console.WriteLine(Hello World); } }
29
Structure of a Class in C#
class ClassName { DataType1 MemberVariable1; ClassType2 Object2; /* A data member can be defined using 1) primitive types (int, float, string ) 2) user defined structures 3) object reference of a class */
ClassName( parameters ) { /* The constructor is used for members initialization during the object creation */ } return-type MethodName( parameters ) { /* All the application logics have to be placed inside the methods. A method must be placed inside a class.*/ } }// End of the class
30
Namespace
Namespaces
Namespaces provide a way to uniquely identify a type Provides logical organization of types Namespaces can span assemblies Can be nested The fully qualified name of a type includes all namespaces
32
Namespaces
The fully qualified name of a type includes all namespaces Namespaces are mainly used to distinguish between the types having same names Within a namespace, the names of all the types should be unique The Base Class Library (BCL) is a standard library available to all languages using the .NET Framework.
namespace Insys.N1 {//is referred to as N1 class C1 { // is referred to as Insys.N1.C1 class C2 { // is referred to as Insys.N1.C1.C2 } } namespace Insys.N2 { //is referred as Insys.N1.N2 class C2 { //is referred as Insys.N1.N2.C2 } Fully Qualified } name }
33
Data Types in C#
Value Types Value types include simple types like char, int, float, enum types, and struct types Variable holds the actual value Reference Types Reference types include class types, interface types, delegate types, and array types Variable holds the reference of memory location
Allocated on stack
Assignment of one value type to another copies the value
Allocated on heap
Assignment of one reference type to another copies the reference
34
Constructor
Constructor
Constructors are used to initialize the data members during the object initialization A class can have any number of constructors The name of the constructor should be same as the class name The constructor does not have return type, not even void To exit from the constructor, return statement return; can be used.
36
Default Constructor
class Employee { public int empID; public float salary; } /* To create an object of Employee class */ Employee empObj ; empObj= new Employee(); empObj
In the above code snippet, Employee() is a constructor It can be confirmed with the fact that its name is same as the class name For the class Employee, no constructor is written A constructor with no parameters will be supplied automatically for a class that is written with no constructor. This constructor is called as Default Constructor. In the above code snippet, Employee() is the default constructor
37
User-defined Constructors
class Employee { public int empID; public float salary; /* user defined constructor with two parameters */ public Employee(int empIDVal, float salaryVal) { empID = empIDVal; salary = salaryVal; Note: } Employee empObj = new Employee(); /* user defined constructor will results in compile time error. with one parameter */ public Employee(int empIDVal) { For a class with user-defined empID = empIDVal; constructors, default parameter-less } constructor will NOT be supplied } // end of class Employee 38
automatically.
39
Access Specifiers
C# provide five access specifiers, they are as follows : public private protected internal protected internal
40
C# Type
string
System Type
System.String
42
Methods
Append() Insert() Remove() Replace()
StringBuilder str = new StringBuilder (hi); str.Append(how are you?) str.Insert(6,How do you do?);
43
String & StringBuilder Best Practices constants for the string literals you use instead of Always declare
enclosing them in .
string status = "ACTIVE"; const string C_STATUS = "ACTIVE";
Avoid String concatenation using + operator, instead use StringBuilder for concatenation
string message = hello";
StringBuilder message; message= new StringBuilder(); message.Append(" hello "); message.Append(" welcome "); message.Append(" to "); message.Append(" Dotnet "); 44
Parameter Types
access-specifier return-type MethodName( parameters ) { /* All the application logics have to be placed inside the methods. A method must be placed inside a class.*/ }
Methods
By default, all the Value Types are passed by values to the methods By default, all the objects are passed by reference to the methods
46
Parameters Types
The default behavior of passing the parameter can be modified using following parameter arguments (also called as method parameter keywords)
out
It can be used to receive more than one processed output from a method
ref
It can be used to pass variables by reference
params
It can be used to pass zero or more values to a single parameter
47
48
49
50
/* A method definition with params */ void Print(int data, params int[] list) { /* print logic statements */ } /* The various ways of invoking the print method - Print(10 ); Print(10, 1, 2, 3, 4); Print(10, 1, 2, 3, 4, 5, 6, 7); int [ ] num = {1, 2, 3, 4}; Print( 10, num);
*/
51
Indexer (1 of 2)
Indexer permits members of an instance of a class or struct to be indexed in the same way as elements of array. Indexers are similar to properties except that the name of the indexer is this followed by a parameter list. The signature of indexer is
<modifier> <return type> this [formal argument list]
The modifier can be private, public, protected or internal The indexer has get and set blocks. The formal-argument-list specifies the parameters of the indexer.
52
Indexer (2 of 2)
A get accessor returns a value. A set accessor assigns a value. The this keyword is used to define the indexers. The value keyword is used to define the value being assigned by the set indexer. Indexers do not have to be indexed by an integer value only; it is up to you how to define the specific look-up mechanism. Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array. C# do not have the concept of static indexers Indexers can be overloaded. A class can have more than one indexer with different signatures
53
Inheritance
Inheritance follows the is-a relationship between classes The parent class is the base class and the inherited class is the derived class
A derived class cannot access the private members of its base class
Inheritance leads to reusability and extensibility of existing code
55
Inheritance
class TechnicalEvangelist : Employee - class Employee is inherited by the class TechnicalEvangelist. Class Employee can be called as Super or Parent or Base class. Class TechnicalEvangelist can be called as Sub or Child or Derived class. All the public & protected members of parent class can be accessed in the child class as local members. Public member is inherited as a public member by the child class Protected member is inherited as a protected member by the child class No multiple inheritance is available.
56
Protected access specifier (1 of A 2)protected member is accessible only inside its class & its descendants
When a class needs a private member with visibility to its descendant classes, protected access specifier can be used
class Employee { private int age; public string name; protected DateTime birthDate; } class TechnicalEvangelist : Employee {
/* name and birthDate, inherited from Employee class, can be accessed here just like any other local member class */ of this Technical Evangelist
}
57
<<Demo : Inheritance>>
empObj.name = "Jack";
//protected member NOT accessible outside the //class, hence results in compile time error
A sealed class is one that cannot be used as a base class. In other words, a sealed class can not be extended further by any other class. Classes can be declared as sealed by putting the keyword sealed before the keyword class in the class definition
sealed class SoftwareEngineer { /* class members are placed here */ } class DotNetSoftWareEngineer : SoftwareEngineer {
/* this class compilation will be a failure as the sealed class can not be inherited */
59
Whenever a child class object gets created, the base class constructor gets invoked (known as constructor chaining).
60
Discussion: Using the given classes when we class Employee { create an object of SoftwareEngin public Employee() class, the output will be { Empoyee Console.WriteLine("Employee"); SoftwareEngineer Reason: } Before executing a constructor of } the derived class, the parent class class SoftwareEngineer: Employee { constructor with no-parameters public SoftwareEngineer() will be automatically executed firs
{ Console.WriteLine("SoftwareEngineer");
}
}
61
Discussion: Using the given classes when we create an object of SoftwareEngin class, the output will be SoftwareEngineer
class SoftwareEngineer :Employee Reason: Even though there is no construc { public SoftwareEngineer() available in Employee class, a constructor with no-parameter is { automatically supplied to it as a Console.WriteLine("SoftwareEngineer"); default constructor. } }
62
class Employee{ public Employee(int empID){ Console.WriteLine("Employee"); does not get complied. The code } } Reason: class SoftwareEngineer: Employee In Employee class, { the parameter-less constructor public SoftwareEngineer(){ is not available Console.WriteLine("SoftwareEngineer"); automatically will not be supplied explicit constructor is available. } }
63
Discussion: Using the given classes when we create an object of SoftwareEngine Class.
class Employee{ public Employee(int empID){ Console.WriteLine("Employee"); Instead of the default constructor, } any other constructors of } the base class can be specified fo execution using the base keyword class SoftwareEngineer: Employee { public SoftwareEngineer():base(1001){
Solution: Before executing a child class constructor, the parameter less constructor of the parent class will be automatically executed firs This behavior can be modified.
Console.WriteLine("SoftwareEngineer"); }
}
<<Demo : Inheritance and constructors>>
64
Polymorphism
Refers to an objects ability to behave differently depending on its type
Poly = many morph = form
Method overloading (1 of 3)
More than one methods within the same class having the same name but different method signatures are termed overloaded methods. Calls to overloaded methods will be resolved during compile time.
Also known as static polymorphism
When we write constructors having different signatures, it is nothing but constructor overloading.
66
Method Overloading (2 of 3)
class MathApp { same method name with different method signature public int Add(int a) { return a+10; } public int Add(int a, int b) { return a + b; } public int Add(int a, int b, int c) { return a + b + c; } }
Note: The correct method to be invoked is chosen based on 67 the parameters.
Method Overloading (3 of 3)
class MathApp { public int Add(int a) { return a+10; } public float Add(int a) { return a + 20; } }
Compiler Error: Just change in return type alone doesnt mean method overloading
68
Method Overriding (1 of 7)
A subclass can modify behavior inherited from a parent class A subclass can create a method with different functionality than the parents method but with the same:
Name Return type Argument list
Method Overriding (2 of 7)
Same method signature in parent and child classes
class Person { public virtual void Print(){ Console.WriteLine("Hi from class Person"); } } class Employee : Person { public override void Print(){ Console.WriteLine("Hi from class Employee"); } }
70
using System; class Person { public virtual void Print(){ Console.WriteLine("Hi from class Person"); } new - hides the } Print method of class Employee : Person { Person class. public new void Print(){ Console.WriteLine("Hi from class Employee"); } override in } SoftwareEngineer class SoftwareEngineer : Employee { class generates public override void Print(){ error Console.WriteLine("Hi from class SoftwareEngineer"); } Note: } A method to be overridden in a child class should be marked as either virtual or override in the parent class.
<<Demo : Method overriding>>
72
class Person { public override void Print(){ Console.WriteLine("Hi from class Person"); } } class Employee : Person { public override void Print(){ Console.WriteLine("Hi from class Error: Employee"); No virtual method is available for overriding }
}
74
class Person { public virtual void Print() { Console.WriteLine("Hi from class Person"); } } class Employee : Person { public override sealed void Print() { Console.WriteLine("Hi from class Employee"); } class SoftwareEngineer : Employee { public override void Print() { Console.WriteLine("Hi from class Software Engineer"); } Error: }
75
76
77
The output of perObj.Print(); depends on the object being pointed by perObj at that instant during the runtime.
<<Demo : Dynamic Method Dispatch>>
78
Person perObj ; Employee empObj; SoftwareEngineer seObj = new SoftwareEngineer(); empObj = seObj; // parent reference to child object perObj = seObj; // grandparent reference to grandchild object perObj.Print(); // prints Hi from class SoftwareEngineer empObj.Print(); // prints Hi from class SoftwareEngineer
79
80
Abstract (1 of 5)
Consider a scenario of the Payroll application. At present, the company has only Technical Evangelist and Software Engineer as employees. The application includes a salary module which calculates the salary based on the role of the employee. The company is thinking of hiring Employees for other roles as well in the future. So the application should be extendible for these category of employees too. To enjoy the extendibility of the application, the need for Dynamic Method Dispatch arises, so the method overriding and so the inheritance.
81
Abstract (3 of 5)
To achieve Dynamic Method Dispatch, we need to have a virtual method in the parent class. In such situations there are circumstances, like GetSalary() method in Employee class, meaningful method body can not be provided to the concerned virtual method. Now we create abstract method, a method declaration with no method body. When an abstract method need to be in a class, that class should be an abstract class.
82
Abstract (4 of 5)
The abstract keyword can be used for method as well as class An abstract method signifies it has no body (implementation), only declaration of the method followed by a semicolon
Abstract (5 of 5)
If a class has one or more abstract methods declared inside it, the class must be declared abstract or an abstract class can be made when a template needs to be described for a group of sub-classes
It must be ensured that no objects require to be created from it
An abstract class cannot be instantiated i.e. objects cannot be created from an abstract class. Reference of an abstract class can point to objects of its sub-classes thereby achieving run-time polymorphism. An abstract class may also have concrete methods, constructors and data members abstract class Employee
{
//Class definition }
84
Abstract Example (1 of 2)
abstract class Employee{ public string SomeMethod() { /* method body */ } public abstract double GetSalary(); } class SoftwareEngineer: Employee{ private string project; public override double GetSalary() { /* method body */ } }
<<Demo : Abstract>>
85
Abstract Example (2 of 2)
abstract class Employee{ public virtual string SomeMethod() { /* method body */ } public abstract double GetSalary(); } class SoftwareEngineer: Employee{ public override string SomeMethod() { /* a new method body */ ERROR } }
<<Demo : AbstractDemo>>
86
Payroll class
Employee Object reference Any Employees child class object SoftwareEngineer object
What is the intention behind creating the Employee class and inheriting it to HR and SoftwareEngineer classes?
87
Under the circumstances of creating a parent class to inherit only for achieving extendable software design through Dynamic Method Dispatch, define the parent as an interface 88 C# allows a class to have many interface parents
Employee
IECCUser
class
Object reference
Object reference
SE object
Intern object
89
Interface (1 of 6) what?
Interface is similar to a pure abstract class that contains only abstract methods The child class has to provide the implementation for all the methods of the interface parent Object of an interface cannot be created. However, object reference of an interface can be created All methods in an interface are public and abstract by default The parent interfaces object reference can point to the object of the child class. Thus providing support to Dynamic Method Dispatch In the inheritance list the class parent should be followed by the interface parents As per the .NET standard, the interfaces name starts with I
90
All the interface members are public by default Interface can inherit another Interface An interface cannot be instantiated
91
} }
94
eccUserRef.RegisterUser();
96
IECCUser
class
Object reference
Object reference
SE object
97
class SoftwareEngineer: IECCUser, IBlogUser Discussion: { IECCUser eccUserRef; void IECCUser.UnRegister(){ IBlogUser blogUserRef; /* changing the ECCUser SoftwareEngineer seObj; table data */ seObj = new SoftwareEngineer( } void IBlogUser.UnRegister(){ /* call the IECCUser /* changing the BlogUser table data */ implementation */ } eccUserRef = seObj; /* rest of the implementation eccUserRef.UnRegister(); is placed here */ 98 }
/* call the IBlogUser implementation */
Make use of an interface when a role needs to be described for other classes, irrespective of the inheritance tree of these classes
99
Exception Handling (1 of 2)
int val1 = 0; int result = 5/val1; int [] myArray = new int[10]; myArray[1000] = 10;
Exception Handling (2 of 2)
Exception is thrown by the program on occurring of an error The exception object that is thrown consists of information about the exception, including type of exception and the state of the program when the error occurred. The runtime environment attempts to find the Exception Handler The exception handler tries to recover from the error or if it finds that the error can not be recovered then provides a gentle exit from the program Helpful in separating the execution code from the error handler
101
try-catch-finally
try { // statements } catch( ExceptionType1 et1) { // statements } /* any number of catch block can be used */ catch( ExceptionType2 et2) { //statements } /* optional block. This gets executed irrespective of occurrence of exception */ finally { // statements }
<<Demo : Exception Handling>>
102
Thank You
The contents of this document are proprietary and confidential to Insys Technologies Ltd. and may not be disclosed in whole or in part at any time, to any third party without the prior written consent of Insys Technologies Ltd. 2008 Insys Technologies Ltd. All rights reserved. Copyright in the whole and any part of this document belongs to Insys Technologies Ltd. This work may not be used, sold, transferred, adapted, abridged, copied or reproduced in whole or in part, in any manner or form, or in any media, without the prior written consent of Insys Technologies Ltd.
103