Introduction to C#

Page 1

1


Agenda          

.Net Framework & CLR Model Design Goals Introduction to C# Program Structure Unified Type System Statements, Expressions & Operators Methods Object Oriented Programming Namespaces & Assemblies Exception Handling 2


.Net Framework & CLR Model An Overview Source Code

Managed Code

VB

C#

C++

Compiler

Compiler

Compiler

Unmanaged Code

Common Language Specification Common Language Runtime JIT Compiler Native Code Operating System Services 3


.Net Framework & CLR Model Explanation

 Microsoft .Net Framework is very well designed that it supports for developing both Windows based applications and Web based applications.  .Net Framework has this exceptional feature that it automatically converts the data types as per the requirement of framework.

 We can even design and run our own language inside the .Net framework because of its amazing architecture.  At present, the .Net framework 4.5 supports more than 25 languages with the most common being C++ , VB , C# and many more. 4


.Net Framework & CLR Model  Framework divided into three parts  Common Language Specification  Common Type System  Common Language Runtime

 Common Language Specification:  It is platform which allows us to run any language in the .Net Framework.  It also provides the facility of interoperability, Garbage Collection, Exception handing and security.  All language uses their own compiler and further this code is converted into common type of code i.e. Common Intermediate Language (CIL) which can be executed by CLR. 5


.Net Framework & CLR Model  Common Type System (CTS):  In the .Net framework, it is possible to use and understand variables and parameters of all the supported languages.  We use more than one language, having a different set of data type, so this is firstly converted to a Common Type System.

 Common Language Runtime (CLR):  It is a Virtual Machine, after the compilation of code it converts it into machine code with the help of JIT compiler.  CLR also provides some extra services like Memory Management, Type safety, exception handing. Thread management and automatic garbage collection. 6


.Net Framework & CLR Model  Managed Code:  Any language that is written in .NET Framework is managed code.  This code is directly executed by CLR with help of managed code execution.  Managed code uses CLR which in turns looks after your applications by managing memory, handling security, allowing cross - language debugging, and so on.

 Unmanaged code:  Includes all code written before the .NET Framework was introduced.  This includes code written to use COM, native Win32, and Visual Basic 6. Because it does not run inside the .NET environment, unmanaged code cannot make use of any .NET managed facilities.

7


Agenda          

.Net Framework & CLR Model Design Goals Introduction to C# Program Structure Unified Type System Statements, Expressions & Operators Methods Object Oriented Programming Namespaces & Assemblies Exception Handling 8


Design Goals Component Orientation

 C# is the first “Component-Oriented” language.  A component is an independent module which can be reuse and deployed.  In Component Oriented language objects are language-level constructs.  It includes multiple classes.  They are language-independent.

 In general, component writer and user don’t know each other, don’t work for the same company, and don’t use the same language.  It enables “one stop programming”. 9


Design Goals Everything is an Object

 Traditional views  C++, Java: Primitive types are “magic” and do not interoperate with objects  Smalltalk, Lisp: Primitive types are objects, but at great performance cost

 C# unifies with no performance cost  Deep simplicity throughout system

 Improved extensibility and reusability  New primitive types: Decimal, SQL…  Collections, etc., work for all types

10


Design Goals Robust and Durable Software

 Garbage collection  No memory leaks and stray pointers

 Exceptions  Error handling is not an afterthought

 Type-safety  No uninitialized variables, unsafe casts

 Versioning  Pervasive versioning considerations in all aspects of language design

11


Design Goals Preservation Of Investment

 C++ heritage  Namespaces, enums, unsigned types, pointers (in unsafe code), etc.  No unnecessary sacrifices

 Interoperability  What software is increasingly about  MS C# implementation talks to XML, SOAP, COM, DLLs, and any .NET language

 Millions of lines of C# code in .NET  Short learning curve  Increased productivity 12


Agenda          

.Net Framework & CLR Model Design Goals Introduction to C# Program Structure Unified Type System Statements, Expressions & Operators Methods Object Oriented Programming Namespaces & Assemblies Exception Handling 13


Introduction to C# Hello World !! using using using using

System; System.Collections.Generic; System.Linq; System.Text;

namespace ConsoleApplication { class Program { static void Main(string[] args) { Console.WriteLine("Hello World !!"); } } }

   

Uses the namespace “System”. Entry point is “Main”. Output goes to the “Console”. File name and Class name need not be identical.

14


Introduction to C# Program Structure

Program File 1

File 2

File 3

namespace A{...}

namespace B{...}

Namespace C{...}

Class X {...}

Class Y {...}

Class Z {...}

15


Agenda          

.Net Framework & CLR Model Design Goals Introduction to C# Program Structure Unified Type System Statements, Expressions & Operators Methods Object Oriented Programming Namespaces & Assemblies Exception Handling 16


C# Program Structure  Namespaces  Contain types and other namespaces

 Type declarations  Classes, structs, interfaces, enums, and delegates

 Members  Constants, fields, methods, properties, indexers, events, operators, constructors, destructors

 Organization  No header files, code written “in-line”  No declaration order dependence 17


Agenda          

.Net Framework & CLR Model Design Goals Introduction to C# Program Structure Unified Type System Statements, Expressions & Operators Methods Object Oriented Programming Namespaces & Assemblies Exception Handling 18


Unified Type System  C# has this really new feature i.e. It follows Unified Type System.  All types are compatible with object  Can be assigned to variables of type object  All operations of type object are applicable to them

 They are basically of two types which can be sub categorized further.  Value Types  Reference Types  Pointers (hardly used)

19


Unified Type System Value Type v/s Reference Type Value Type

Reference Type

variable contains

value

reference

stored on

stack

heap

initialisation

0, false

null

assignment

copies the value

copies the reference

Example

int i = 20; int j = i;

string s = “Hello�; string s1 = s;

I

20

s

j

20

s1

20 20

Hello 20


Unified Type System Value Types

• Simple Types • Enums • Structs

Unified Type System Reference Types

• • • •

Classes Interfaces Arrays Delegates 21


Value Types Simple Types & their Compatibility

22


Value Types Enumerations Declaration enum Color {red, blue, green} // values: 0, 1, 2 enum Access {personal=1, group=2, all=4}

Enums can be defines as “List of Named Constants �.

Use: Color c = Color.blue; // enumeration constants must be qualified Access a = Access.personal | Access.group; if ((Access.personal & a) != 0) { Console.WriteLine("access granted"); } 23


Value Types Structs Declaration Struct Point { public int x, y;// fields public Point (int x, int y) { this.x = x; this.y = y; }//constructor public void MoveTo (int a, int b) { x = a; y = b; }// methods }

Use: Point p = new Point(3, 4); // constructor initializes object on the stack p.MoveTo(10, 20); // method call

24


Reference Types Classes

Declaration Class Rectangle { Point origin; public int width, height; public Rectangle() { origin = new Point(0,0); width = height = 0; } public Rectangle(Point p, int w, int h) { origin = p; width = w; height = h; } public void MoveTo (Point p) { origin = p; }}

Use: Rectangle r = new Rectangle(new Point(10, 20), 5, 5); int area = r.width * r.height; r.MoveTo(new Point(3, 3)); 25


Classes v/s Structs Classes

Structs

Classes are of Reference Types. Objects are stored in the form of heap

Structs are of Value Types. Objects stored on the stack.

It supports inheritance.

No inheritance in structs, but they are compatible with object.

We can implement interfaces as well

Structs can also implement interfaces

Classes may have destructors

No destructors are allowed

26


Arrays

27


Boxing and Unboxing

28


Agenda          

.Net Framework & CLR Model Design Goals Introduction to C# Program Structure Unified Type System Statements, Expressions & Operators Methods Object Oriented Programming Namespaces & Assemblies Exception Handling 29


Statements Simple Statements

 Empty Statement ;

// ; is a terminator statement

 Assignment Statement X = 5* y +4;

 Method Call

30


Statements If Statement

31


Statements Switch Statement

32


Statements Switch with Gotos

33


Statements Loops

34


Statements foreach

35


Statements jumps

36


Statements return

37


Agenda          

.Net Framework & CLR Model Design Goals Introduction to C# Program Structure Unified Type System Statements, Expressions & Operators Methods Object Oriented Programming Namespaces & Assemblies Exception Handling 38


Methods Methods

 A method is a code block that contains a series of statements. All code executes in a method  Constructors, destructors and operators are special types of methods  Properties and indexers are implemented with get/set methods

 Methods have argument lists.  Methods can return a value  Only if return type is not void

 The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started. 39


Methods Arguments v/s Parameters

ďƒ˜ The method definition specifies the names and types of any parameters that are required. ďƒ˜ When calling code, calls the method, it provides concrete values called arguments for each parameter. void int Sum( int a, int b ) { return (a + b); }

void int Main() { int c = Sum( 4, 7 ); }

Parameters

Arguments

40


Methods Passing Arguments

 Arguments can be passed through three methods in c#  By Value  By Reference  Out Modifier

41


Methods Passing by value

 By default in C# arguments are passed by value, which basically means that when you pass on a variable to a function call, you are actually sending a copy of the object, instead of a reference to it.  This also means that you can make changes to the parameter from inside the function, without affecting the original object you passed as a parameter.  i.e. for value types, passed variables cannot be modified from within a method call, all changes are made to variables copy.

42


Methods Passing by value void Main(string[] args) { int a = 5; IncrementByOne(a); Console.WriteLine(a); } void IncrementByOne(int a) { a = a + 1; }

 We assigned value “5” to an integer “a”, and passed it as an argument to a function “IncrementByOne”, which should add “1” to it.  But it does not, since the variable is passed as value, i.e. Instead of passing the variable itself, we have passed a copy of it to the function, and the number “1” is added to the copy, and not the original variable. 43


Methods Passing by reference

 Passing by reference causes a method to refer to the same variable that was passed into the method (and not it’s copy), i.e. any changes made to the variable in the method will be reflected in that variable.  To pass by reference, both the passed argument and receiving parameter must specify the “ref” keyword. void Main(string[] args) { int a = 5; IncrementByOne(ref a); Console.WriteLine(a); } void IncrementByOne(ref int a) { a = a + 1; }

44


Methods Out Modifier

 The ”out” keyword causes arguments to be passed by reference. This is similar to the ”ref” keyword, except 2 major differences:  “ref” requires that the variable be initialized before being passed, whereas even initialized variables can be passed with “out”.  Although variables passed as an ”out” arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.

 To use an out parameter, both the method definition and the calling method must explicitly use the out keyword

45


Methods Usage of Ref vs Out Modifier

Χ Invalid Usage void Main(string[] args) { int a; IncrementByOne(ref a); }

Χ Invalid Usage Un-initialized variable “a” cannot be passed as reference using “ref” keyword

 Correct Usage void Main(string[] args) { int a; IncrementByOne(out a); }

Even un-initialized variable “a” can be passed as reference using “out” keyword

void IncrementByOne(out int a) { // Do Nothing }

 Correct Usage

Parameters using “out” keyword cannot be left un-assigned

Parameters using “ref” keyword can be left un-assigned

void IncrementByOne(ref int a) { // Do Nothing }

46


Methods Overloaded Methods

 A type may overload methods, i.e. provide multiple methods with the same name  Each must have a unique signature  Signature is based upon arguments only, the return value is ignored void Print(int i); void Print(string a); void Print(char b); void Print(float c); int Print(float c); // Error 47


Methods Parameter Arrays

ďƒ˜ Methods has variable number of arguments, called a parameter array. ďƒ˜ params keyword is used to declare parameter array. ďƒ˜ It should be the last argument. int Sum(params int[] arr){ int sum = 0; foreach(int i in arr) { sum += i; return sum; }} int sum = Sum(34, 56, 67); 48


Agenda          

.Net Framework & CLR Model Design Goals Introduction to C# Program Structure Unified Type System Statements, Expressions & Operators Methods Object Oriented Programming Namespaces & Assemblies Exception Handling 49


Object Oriented Programming classes and objects class Maths{ int length; int width; public int calculateArea() { int area = length * width; return area; }} Maths maths = new Maths(); maths.length = 20; maths.width = 10; maths.area(); 50


Object Oriented Programming classes and objects

 Class is a data structure that encapsulates a set of data and behaviours that belong together as a logical unit.  A class is a blueprint and objects are used to create instances at run time.  As a class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory.  An object can be created by using new keyword followed by name of the class

51


Object Oriented Programming What are Members?

 Classes have members that represent their data and behaviour of an object.  A class's members include all the members declared in the class, along with all members (except constructors & destructors) declared in all classes in its inheritance hierarchy. List of class’s members Fields

Methods

Indexers

Constants

Events

Constructors

Properties

Operators

Destructors

Nested Types

52


Object Oriented Programming Access Modifiers

All type members have an accessibility level, which tells whether they can be used from other code in one assembly or other assemblies.  public  The type or member can be accessed by any other code in the same assembly or another assembly that references it.

 private  The type or member can be accessed only by code in the same class.

 protected  The type or member can be accessed only by code in the same class, or in a class that is derived from that class. 53


Object Oriented Programming Access Modifiers

 internal  The type or member can be accessed by any code in the same assembly, but not from another assembly.

 protected internal  The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly.  It must take place through an instance of the derived class type.

54


Object Oriented Programming Fields

 A field is a variable of any type that is declared directly in a class.  A class may have instance fields or static fields or both.  Instance fields are specific to an instance of a type. A class T, with an instance field F, there can be two objects of type T, and modify the value of F in each object without affecting the value in the other object.  On the other hand, a static field belongs to the class itself, and is shared among all instances of that class.  Fields store the data that must be accessible to more than one class method and must be stored for longer than the lifetime of any single method. 55


Object Oriented Programming Constants

 Constants are the values which are known at compile time and do not change for the life of the program.  Constants are declared with the const modifier.  Only the C# built-in types like int, string etc. may be declared as const.  User-defined types, like classes, structs, and arrays, cannot be const because in classes and structs object should be of reference type, and object is created at runtime. For arrays, they only store addresses whose values can be changed at the runtime.  C# does not support const methods, properties, or events. 56


Object Oriented Programming Constants

class Calendar { public const int months = 12; } ďƒ˜ In this example, the constant months is always 12, and it cannot be changed. ďƒ˜ When the compiler encounters a constant identifier in C# source code, it substitutes the literal value directly into the intermediate language (IL) code that it produces. Because, there is neither a reference nor variable address associated with a constant at run time. 57


Object Oriented Programming 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. ďƒ˜ In the next example, the TimePeriod class stores a time period. Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds. 58


Object Oriented Programming Properties class TimePeriod { private double seconds; public double Hours { get { return seconds / 3600; } set { seconds = value * 3600; } }

}

ďƒ˜ Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. 59


Object Oriented Programming Properties

ďƒ˜ A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. ďƒ˜ The value keyword is used to define the value being assigned by the set accessor. ďƒ˜ Properties that do not implement a set accessor are read only.

60


Object Oriented Programming Static Class and Members

 Static Class  Is basically the same as a non-static class, but a static class cannot be instantiated.  As there is no instance variable, we can access the members of a static class by using the class name itself.  Contains static members only.

 Static Members  A non-static class can contain static methods, fields, properties, or events and callable on a class even when no instance of the class has been created.  Only one copy of a static member exists, regardless of how many instances of the class are created. 61


Object Oriented Programming Constructor

 Constructors are class methods (with same name as class) that are executed when an object of a class or struct is created.  A class or struct may have multiple constructors that take different arguments.  Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.  If a class doesn’t define any constructors, an implicit parameterless constructor is created

62


Object Oriented Programming Static Constructor

 A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only.  It is called automatically before the first instance is created or any static members are referenced.  They are supposed to be parameterless.  A static constructor cannot be called directly.  A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

63


Object Oriented Programming Destructor

 A destructor is a method that is called before an instance is garbage collected  Used to clean up any resources held by the instance, do bookkeeping, etc.  Only classes, not structs can have destructors. class createDestructor { ~createDestructor() { Console.WriteLine("Destroyed", this); } } 64


Object Oriented Programming Object & Collection Initializers

ďƒ˜ Object Initializers  Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor. class Cat { public int Age { get; set; } public string Name { get; set; } } List<Cat> cats = new List<Cat>(); cats.add(new Cat(){ Age = 5, Name = "Loofa"}); cats.add(new Cat(){ Age = 2, Name = "Kitty"}); 65


Object Oriented Programming Object & Collection Initializers

ďƒ˜ Collection Initializer: To do previous example with collection initializer, it becomes more simpler. List<Cat> cats = new List<Cat>() { cats.add(new Cat(){ Age = 5, Name = "Loofa"}), cats.add(new Cat(){ Age = 2, Name = "Kitty"}) };

66


Agenda          

.Net Framework & CLR Model Design Goals Introduction to C# Program Structure Unified Type System Statements, Expressions & Operators Methods Object Oriented Programming Namespaces & Assemblies Exception Handling 67


Namespaces & Assemblies

68


Agenda          

.Net Framework & CLR Model Design Goals Introduction to C# Program Structure Unified Type System Statements, Expressions & Operators Methods Object Oriented Programming Namespaces & Assemblies Exception Handling 69


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.