C Course Material0209

42
C#.NET

Transcript of C Course Material0209

Page 1: C Course Material0209

C#.NET

Page 2: C Course Material0209

Week 1

What is .NET Framework? It is kind of environment in which a

developer can develop almost any kind of application. For ex

• Console Applications• Windows Applications• Database Applications• Web Applications• Windows & Web Services• XML Web Services

Page 3: C Course Material0209

Week 1

Different Versions of .NET Framework.NET Framework 1.0 (VS 2002).NET Framework 1.1 (VS 2003).NET Framework 2.0 (VS 2005).NET Framework 3.0 (VS 2008).NET Framework 3.5 (VS 2008).NET Framework 4.0 (VS 2010)

Page 4: C Course Material0209

Week 1

.NET Framework ArchitectureThe framework is contains so many

components. One of the most important is CLR (Common Language Runtime)

Page 5: C Course Material0209

Common Language RuntimeIn the central of .NET Framework its runtime execution environment, responsible for execution of any .NET application.Before execution by CLR any source code compile in two steps:

• Compilation of source code in IL Code• Compilation of IL code to platform specific code by CLR

Source Code in .NET Compatible Language

Language Compiler

IL Intermediate language Code

Twice Compile with JIT (Just in time compiler)

Native Machine Code

Page 6: C Course Material0209

Week1

What is IL or MSIL Code and what are its advantages?Microsoft intermediate language shares with Java byte code the idea that it is a low-level language with a simple syntax (based on numeric codes rather than text), which can be very quickly translated into native machine code. Having this well-defined universal syntax for code has significant advantages

Advantages of ILPlatform IndependencePerformance Improvement

Language interoperability

Page 7: C Course Material0209

Week 1

Platform Independence Platform Independence means a application having capability to run on different-2 machine and different-2 environment. It means that the same file containing byte code instructions can be placed on any platform; at runtime the final stage of compilation can then be easily accomplished so that the code will run on that particular platform. So on particular platform we need JIT, it is in CLR, it is in Framework ie it necessary to have .NET framework for execution of any .NET application.In other words, by compiling to IL we obtain platform independence for .NET, in much the same way as compiling to Java byte code gives Java platform independence.

You should note that the platform independence of .NET is only theoretical at present because, at the time of writing, a complete implementation of .NET is only available for Windows. However, there is a partial implementation available

Page 8: C Course Material0209

Week 1

Performance Improvement Although we previously made comparisons with Java, IL is actually a bit more ambitious than Java byte code. IL is always Just-In-Time compiled (known as JIT compilation), whereas Java byte code was often interpreted. One of the disadvantages of Java was that, on execution, the process of translating from Java byte code to native executable resulted in a loss of performance (with the exception of more recent cases, where Java is JIT compiled on certain platforms).

Instead of compiling the entire application in one go (which could lead to a slow start-up time), the JIT compiler simply compiles each portion of code as it is called (just-in-time). When code has been compiled once, the resultant native executable is stored until the application exits, so that it does not need to be recompiled the next time that portion of code is run

Page 9: C Course Material0209

Week 1

Language Interoperability In .NET framework we can use more than one language (near

about 64 languages) so the unique feature of .NET is that we can inter operate the different-2 language code.The use of IL not only enables platform independence; it also facilitates language interoperability. Simply put, you can compile to IL from one language, and this compiled code should then be interoperable with code that has been compiled to IL from another language.

Page 10: C Course Material0209

Till now we have seen .NET framework supports more than one languages and the language will compile to IL, since any languagethat targets .NET would logically need to support the main characteristics of IL too. Here are the important features of IL:

Object-orientation and use of interfaces Strong distinction between value and reference types Strong data typing Error handling through the use of exceptions Use of attributes Let’s now take a closer look at each of these characteristics.

Page 11: C Course Material0209

Object-orientation and use of interfaces

The particular route that Microsoft has chosen to follow for IL is that of classic object-oriented programming, with single implementation inheritance of classes.

Strong distinction between value and reference typesAs with any programming language, IL provides a number of predefined primitive data types. One characteristic of IL, however, is that it makes a strong distinction between value and reference types.

Value types are those for which a variable directly stores its data, while reference types are those for which a variable simply stores the address at which the corresponding data can be found.

Specifications of IL

Page 12: C Course Material0209

Strong data typing What we mean by strong data typing is that all variables are clearly

marked as being of a particular, specific data type (there is no room in IL, for example, for the Variant data type recognized by Visual Basic and scripting languages). In particular, IL does not normally permit any operations that result in ambiguous data types.

Although enforcing type safety might initially appear to hurt performance, in many cases the benefits gained from the services provided by .NET that rely on type safety far outweigh this performance loss. Such services include:

Language interoperability Garbage collection Security

Specifications of IL

Page 13: C Course Material0209

The Importance of strong data typing for language interoperability

This data type problem is solved in .NET through the use of the Common Type System (CTS). The CTS defines the predefined data types that are available in IL, so that all languages that target the .NET Framework will produce compiled code that is ultimately based on these types.For the example that we were considering before, Visual Basic .NET’s Integer is actually a 32-bit signed integer, which maps exactly to the IL type known as Int32. This will therefore be the data type specified in the IL code. Because the C# compiler is aware of this type, there is no problem. At source code level, C# refers to Int32 with the keyword int, so the compiler will simply treat the Visual Basic .NET method as if it returned an int.

Specifications of IL

Page 14: C Course Material0209

C# is specifically design to work with .NET framework it is having its own programming elements

KeyWordsPredefine words in the language for e.g. void, for, delegate, class etc.

IdentifierIt is the name of the programming unit, may be name of variable, constant, namespace, class, method, property etc.Ii follows two naming styles in C#

i) PascalCasing ii) camelCasing Literals

Any constant value refer as literal may be numeric or alphabetic.13, 23.45 are numeric constant, “India” is string constant

Operator Predefine symbols in the language, used to perform certain actions

for e.g. +, %, *….. etc

Week1

Page 15: C Course Material0209

Variables

Variable are the named stored location in memory whose contents can be change during program execution.

Data TypeRepresent what kind of value the variable will store.

types

user define predefine

value type reference type

10 n This Value can be change

Page 16: C Course Material0209

Syntax for declarationdatatype variablename;In C# program you declare the variable at following placesclass Test{

private int a; // Field level variablepublic void M1(){

int b; // local variable for a methodfor(int i=0;i<10;i++) // local variable for a block{

}}

}

Variable Declaration, Scope and default value of Variable

Page 17: C Course Material0209

Scope of variableThe accessibility & availability of a variable in a program is called scope of variable.

In C# program variable may have three kind of scope1. Field level scope2. Local scope for a method3. Local scope for a block class Test{

private int a; // Field level Scopepublic void M1(){

int b; // local scope for a methodfor(int i=0;i<10;i++) // local scope for a block{

}}

}

Variable Declaration, Scope and default value of Variable

Page 18: C Course Material0209

Default value of variableIn c# field level variable having their default value according to datatype

while local variable will not have default or garbage value. For ex.class Test{

private int a; // Field level Scopepublic void M1(){

int b; // local scope for a methodConsole.WriteLine(a); // default value ie zeroConsole.WriteLine(b); // compilation error// compiler will force us to initialize local variable before use Console.ReadLine();

}}

Variable Declaration, Scope and default value of Variable

Page 19: C Course Material0209

Value Type: Value types are those for which a variable directly stores its data,

int i=10; // value typeint j= i;

here i & j both are the value type.

Reference Type: Reference types are those for which a variable simply stores the

reference at which the corresponding data can be found.Test t1;

10 i

10 j

Page 20: C Course Material0209

Example of reference type

Test t1; //reference type t1 is created and it can refer any object of /// class Test type.

t1= new Test(); Test t2; t2=t1 // only reference transforms

t1

t2

Object of Test class

Page 21: C Course Material0209

Type Casting

Boxing:When Value type is converted into reference type then it is called boxing.int n=10;object ob = (object)n; // Boxing

Unboxing:When boxed object again converted into value type than it is called unboxing. int j = (int)ob;

Page 22: C Course Material0209

Memory organization: Stack & Heap concepts

In c# program memory divided into logical regions, stack and heap area

Value types and reference allocated memory in stack area while reference type gets memory in heap area.

i

jt1

t2

stack heap

Page 23: C Course Material0209

types

Predefine User define

Value type Reference type class struct(Ref type) (value

type)

string object

sbyte short int long byte ushort uint ulong

float double decimal

char bool

Data Types

Page 24: C Course Material0209

Console Input/Output

Input: we have Console.ReadLine() method for taking input from consoleThis method will return string.Output: For output we have Console.WriteLine() method.The use of these two methods expalin with help of simple programnamespcae ConsoleIO{

class InputOutput{

public static void Main(){

int a, b;//inputConsole.WriteLine(“Enter two numbers”);a= int.Parse(Console.ReadLine()); // type casting becoz Readline return

//stringb= int.Parse(Console.ReadLine());int c= a+ b;// outputConsole.WriteLine(c); //orConsole.WriteLine(“The sum of two numbers==>” +c.ToString());//orConsole.WriteLine(“The sum of {0} and {1} is {0}”, a,b,c);//orConsole.WriteLine(“The sum of {0,5} and {1,5} is {0,5}”, a,b,c);//orConsole.WriteLine(“The sum of {0,5:c} and {1,5:c} is {0,5:c}”, a,b,c);

}}

}

Page 25: C Course Material0209

Classes and Objects

Object It is collection of data and its functions. or any real world entity.

ClassClass are the way through which we can implement our object.

orClasses are like blue print or template through which you can obtain the information about object.

orWhenever we create a class a new type will be created and it will be reference type.

Object Data

Its Functions

Page 26: C Course Material0209

Classes and Objects

Class Declaration SyntaxAccess Modified class ClassName{

AccessModifier data1; AccessModifier data2;……

AccessModifier MemberFunction1();AccessModifer MemberFucntion2();…..

}Access Modifier: Tell where the type and member are available. In C# we

are having 5 modifiersi) private ii) protected iii) public iv) internal

v) protectedinternal

Page 27: C Course Material0209

Classes and Objects

In a C# class we can write following types of data members and member functions.

C# Class

Data Members Member Functions

Field level variables constant events

Methods Properties Constructors Finalizer

Page 28: C Course Material0209

Classes and Objects

Static and Non static (instance) Data Member and member function of the classNon static member:

When we create object than new copy of non static members is created.Static Member:

Once copy of static member will created & it will be share among all the objects.for e.g.class Test{

private int a; // non static memberprivate static int b;

}Test t1= new Test();Test t2 = new Test();

t1 a

t2a

b

Page 29: C Course Material0209

Methods in C#

Methods: To perform any general operation on data member of the class we can write methods

Syntax for writing methosAccessModifier [static] return type MethodName(argument(s) list){

// implementation of methods}Static and non Methods:

Static method can access only static members while non static methods can access both types of data members

Static method can be call without creating object while non static method can be call with object or instance of class only.

Static method :ClassName.MethodName();

Non static or instance method :object.MethodName();

Page 30: C Course Material0209

Methods in C#

Methods Calling Mechanism:In c# method can be call with two mechanism 1. Call by value2. Call by reference depend on the argument of method

Method argument

reference type value type Can be call only with can be value or reference mechanism reference mechanism By default with value mechanism, for

reference mechanism we can use ref keyword

Page 31: C Course Material0209

Methods in C#

Practical example illustrate method calling mechanismusing System;using System.Collections.Generic;using System.Text;

namespace CallByValueRefEx{ class Program { public static void ChngeData(int[] ar, ref int i) // with ref keyword can also call, use value mechanism { i = 100; ar[0] = 100; } static void Main(string[] args) { int i = 0; int[] a = new int[2]; a[0] = 10; a[1] = 20; Console.WriteLine("The value of variable and array before calling method are --"); Console.WriteLine("i= {0} \nar[0]={1}", i, a[0]); ChngeData(a, ref i); Console.WriteLine("The value of variable and array after calling method are --"); Console.WriteLine("i= {0} \nar[0]={1}", i, a[0]); Console.ReadLine();

} }}

Page 32: C Course Material0209

PropertyIt is a special kind of get & set method use to read or write data member.

Syntax for writing propertyAccess Modifier type PropertyName{

get{}set{}

}To access property: object.PropertyName // get property called

object.PropertyName=someValue // set PropertyProperty may be static or may be non static, in case static can be call with

class name.

Properties

Page 33: C Course Material0209

Example to illustrate the concept of Propertyclass Demo{

private int rollNo;// property for above memberpublic int RollNo{

get{

return rollNO;}set{

rollNo=value;}

}public static void Main(){

Demo d1= new Demo(); d1.RollNo=134; // set propertyConsole.WriteLine(d1.RollNo); // get property

}}

Properties

Page 34: C Course Material0209

Constructor It is a special kind of method whose name is same as class

name it do not have any return type. Default zero argument constructor exist when we not write

constructor in the class. It will invoke automatically when object is created. It may have or may not have argument It can be overlaoded.Syntax for writing property

Access Modifier ClassName( [argement(s)] ){

}

Constructor

Page 35: C Course Material0209

this keywordIt is the common reference for current object.

Two uses of this keyword In the constructor to resolve the scope of class member. To call same class constructor in constructor overloading.

this keyword

Page 36: C Course Material0209

this keywordIt is the common reference for current object.

Two uses of this keyword In the constructor to resolve the scope of class member. To call same class constructor in constructor overloading.

Struct in c#

Page 37: C Course Material0209

Decision Statements This type of statement can be achieve with if..else and switch

statementSyntax for if statementif(condition){

s1; // any valid c# statement} Syntax of if…else statementif(condition){

s1; s2;}else{

s3; s4;}

Page 38: C Course Material0209

Syntax of nested if…else statementif(condition1){

s1;}else{

if(condition2){ s2;}else{

if(condition3){

s4;}else

s5;}

}

Page 39: C Course Material0209

Switch StatementUse to check multiple conditions with only match for equality.switch (variable){

case value of variable:s1; s2;break;

case value of variable:s3;s4;break;

default:s5;break;

}

Page 40: C Course Material0209

Iteration statementThe purpose of these type statement is that we written one time

but it will execute more than one time, this can be achieve with the help of loop statement in c# we are having four types of loops

i) for loop ii) while loop iii) do while loop iv) foreach loop

Page 41: C Course Material0209

for loopSyntax

for(initilization of loop variable; condition; increment/ decrement){

s1; s2; s3;}

while LoopSyntax

while(condition){

s1; s2; s3;}

do while loop Syntax do{

s1; s2;} while (condition);

Page 42: C Course Material0209

foreach loop

This loop is new in c#, it use to iterate items from any collections, without providing conditional statement and increment of decrement statement, its Syntax isforeach(local variable in collection){

s1; s2; }