Vous êtes sur la page 1sur 30

Chapitre 1.

Introduction C# et Visual Studio 2012

Chapitre 1

Introduction au .NET Framework,


Visual Studio 2012,
et au langage C#

Mohamed Romdhani
MCSD Web Applications .NET 4.5

Contenu
Le .NET Framework
Prsentation de Visual Studio
Introduction au langage C#

M. Romdhani, Janvier 2014

Chapitre 1. Introduction C# et Visual Studio 2012

Le .NET Framework

M. Romdhani, Janvier 2014

Quest ce que .NET ?


Dfinition : [dot-net]

.NET est une plateforme


complte pour dvelopper,
dployer et excuter des
Applications Web, Windows,
Mobiles et serveur

Un Modle de programmation unifi


Une plate-forme de dploiement et dexcution
Framework .NET : Gratuit & intgr Windows
M. Romdhani, Janvier 2014

Chapitre 1. Introduction C# et Visual Studio 2012

Architecture

Application
.NET Framework
OS
5

M. Romdhani, Janvier 2014

Components of the Framework

Frameworks
WinForms

WPF

WCF

etc.

VB

C#

Ruby /
Python

Base Class Library


Core types and services

etc.

Visual Studio

ASP.NET

Languages

Common Language Runtime


Assembly load and execution
M. Romdhani, Janvier 2014

Chapitre 1. Introduction C# et Visual Studio 2012

Historique du .NET Framework


et de Visual Studio
Version

Version Number

Release Date

Visual Studio

1.0

1.0.3705.0

13.02.2002

Visual Studio .NET 2002

1.1

1.1.4322.573

24.04.2003

Visual Studio .NET 2003

2.0

2.0.50727.42

07.11.2005

Visual Studio 2005

3.0

3.0.4506.30

06.11.2006

3.5

3.5.21022.8

19.11.2007

Visual Studio 2008

4.0

4.0.30319.1

12.04.2010

Visual Studio 2010

4.5

4.5.40805

12.09.2012

Visual Studio 2012

M. Romdhani, Janvier 2014

Historique dvolution de la CLR

SP1
3.5
3.0
.NET 1.0

.NET 1.1

.NET 2.0

4.5
.NET 4

.NET 4

2002

2003

2005-08

2008 CTP!

2008 CTP!

CLR 1.0

CLR
1.1

CLR 2.0

CLR 4

CLR 4.5

M. Romdhani, Janvier 2014

Chapitre 1. Introduction C# et Visual Studio 2012

Caractristiques de la plateforme
.Net
Les langages gnrent
dsormais un langage
commun, bas sur des types
communs : le MSIL
(Microsoft Intermediate
Language)
Ces modules en MSIL sont
compils en code machine
la vole ( just in time )
Astuce : il est possible de
lire le MSIL avec ildasm
Astuce : il est possible de
dcompiler avec reflector

M. Romdhani, Janvier 2014

Common Language Runtime (CLR)


Common Type System
JIT (just-in-time) Compiler
Code access security
Garbage Collection
Class Loader
COM Interoperability

M. Romdhani, Janvier 2014

10

Chapitre 1. Introduction C# et Visual Studio 2012

JIT Compilation and Runtime


.exe

Source
Code

Compiler

.cs

csc.exe
(Compile time)

MSIL

MSIL
containing
.NET
Assembly

Run time
JITter

CLR
En ter Title Here

Memory

M. Romdhani, Janvier 2014

11

MSIL
.NET Languages JITting MSIL
Not an executable
Needs CLR
After JIT compilation (Just-In-Time Compilation)

CPU independent
Advantages
Platform independent / any client (that has a suitable framework)
Optimization (even smart compilation)

M. Romdhani, Janvier 2014

12

Chapitre 1. Introduction C# et Visual Studio 2012

What does MSIL look like?


ILDASM.exe

M. Romdhani, Janvier 2014

13

What is the Common Type System?


A set of common types
any language that runs in CLR should implement
no syntax specified
Languages often define aliases
For example
CTS defines
System.Int32
4 byte integer
C# defines int as an
alias of System.Int32
Value Types are
allocated on the Stack
Reference Types are
allocated on the Heap

M. Romdhani, Janvier 2014

14

Chapitre 1. Introduction C# et Visual Studio 2012

What is an assembly ?
Building blocks of .NET Framework applications
Collection of types and resources that form a logical unit of functionality

MyAssembly .dll OR .exe


Assembly signed
with a digital
certificate

MyClassA
MyResource
MyClassB
V 1.1.254.1

Assembly version
<major>.<minor>.<build>.<revision>
15

M. Romdhani, Janvier 2014

Organisation du Framework .NET

System

System.IO
Entres/Sorties

System.Security

System.Collections
Listes, tableaux, etc.

System.Resources
Traduction automatique

System.Text
StringBuilder
System.Text.RegularExpressions

System.Configuration
Accs aux fichiers de config XML.

System.Xml

System.Xml.Schema
Pour les XSD

Transformation dun objet en XML et


inversement.

System.Xml.XPath

System.Xml.Xsl

Parcours optimis dun flux XML.

Transformation XSLT : formatage


dun flux XML.

System.Data

ADO.NET

System.Data.OracleClient

M. Romdhani, Janvier 2014

System.Xml.Serialization

Se trouve dans une assembly


distincte.

System.Data.Sql

16

Chapitre 1. Introduction C# et Visual Studio 2012

What Tools Does the .NET Framework


Provide?

Caspol.exe

Makecert.exe

Ngen.exe
Gacutil.exe

Ildasm.exe

Sn.exe

M. Romdhani, Janvier 2014

17

Prsentation de Visual Studio

M. Romdhani, Janvier 2014

18

Chapitre 1. Introduction C# et Visual Studio 2012

Visual Studio 2012 IDE Overview

Visual Studio 2012:


Intuitive IDE that enables developers to quickly build
applications in their chosen programming language

Visual Studio 2012 features:


Rapid application development
Server and data access
Debugging features
Error handling
Help and documentation

M. Romdhani, Janvier 2014

19

Visual Studio 2012 IDE Overview


Integrated Development Environment (IDE)

Project templates
Wizards
Debugging
IntelliSense

M. Romdhani, Janvier 2014

20

10

Chapitre 1. Introduction C# et Visual Studio 2012

The Structure of Visual Studio Projects and


Solutions
Visual Studio Solution
Visual Studio solutions are wrappers for .NET projects
Visual Studio solutions can contain multiple .NET projects
Visual Studio solutions can contain different types of .NET projects

ASP.NET project

WPF project

.aspx

.xaml

.csproj

.aspx.cs .config

.csproj

.xaml.cs .config

Console project
.cs

.csproj
.config
21

M. Romdhani, Janvier 2014

Visual Studio 2012 IDE Overview


Visual Basic Windows Forms Application
(selected)

M. Romdhani, Janvier 2014

Default project name


(provided by Visual Studio)

Description of selected project


(provided by Visual Studio)

22

11

Chapitre 1. Introduction C# et Visual Studio 2012

Visual Studio 2012 IDE Overview

Menu in the menu bar

(cont.)

Solution Explorer window

Form (Windows
Forms application)

M. Romdhani, Janvier 2014

Properties
window

23

Menu Bar and Toolbar

The set of menus displayed depends on what you are currently doing in the IDE

You can access common commands from the toolbar icons

M. Romdhani, Janvier 2014

24

12

Chapitre 1. Introduction C# et Visual Studio 2012

Visual Studio 2012 Useful Shorcuts


Build & Debug Shortcuts
Set/Unset Breakpoint (F9)
Build (F6 or Ctrl +Shift +B)
Start Debugging (F5)
Start Without Debugging (Ctrl +F5)
Stop Debugging (Shift +F5)
Continue (F5)
Step Over (F10)
Step Into (F11)
Step Out (Shift +F11)
Comment / Uncomment (Ctrl +K, C / Ctrl +K, U)
Go to Definition (F12)
Find all References (Shift + F12)
Auto Format (Ctrl +K, D or Ctrl +E, D)
Surround With (Ctrl +S) Surrounds a block of code with a code snippet.
M. Romdhani, Janvier 2014

25

Introduction au langage C#

M. Romdhani, Janvier 2014

26

13

Chapitre 1. Introduction C# et Visual Studio 2012

Purpose of C#
C#
C# is the language of choice for many developers who build
.NET Framework applications
C# uses a very similar syntax to C, C++, and Java
C# has been standardized and is described by the ECMA334 C# Language Specification

27

M. Romdhani, Janvier 2014

C# au fil de lhistoire

[http://jlambert.developpez.com/tutoriels/dotnet/nouveautes-csharp-5/]

M. Romdhani, Janvier 2014

28

14

Chapitre 1. Introduction C# et Visual Studio 2012

The Structure of a Console Application

Bring System namespace into scope


using System;
Namespace declaration
namespace MyFirstApplication
{
class Program
Program class declaration
{
static void Main(string[] args)
{
}

Main method declaration

}
}

M. Romdhani, Janvier 2014

29

Key language features


Unified object system
Everything type is an object, even primitives

Single inheritance
Interfaces
Specify methods & interfaces, but no implementation

Structs
A restricted, lightweight (efficient) type

Delegates
Expressive typesafe function pointer
Useful for strategy and observer design patterns

M. Romdhani, Janvier 2014

30

15

Chapitre 1. Introduction C# et Visual Studio 2012

Hello World example


public class HelloWorld
{
public static void Main()
{
// Use the system console object
System.Console.WriteLine(Hello, World!);
}
}
Creates a new object type (class) called HelloWorld.
It contains a single method, called Main.
Main contains one line, which writes Hello, World! on the display.
The method that performs this action is called WriteLine.
The WriteLine method belongs to the System.Console object.
The keyword static means that the method Main can be called even if there is no
current instance of the class. Its a class method, not an instance method.
The line beginning with // is a comment, and does not execute.

M. Romdhani, Janvier 2014

31

Syntax
Case-sensitive
Whitespace has no meaning
Sequences of space, tab, linefeed, carriage return

Semicolons are used to terminate statements (;)


Curly braces {} enclose code blocks
Comments:
/* comment */
// comment
/// <comment_in_xml>
Automatic XML commenting facility

M. Romdhani, Janvier 2014

32

16

Chapitre 1. Introduction C# et Visual Studio 2012

Classes and Objects


A class combines together
Data
Class variables

Behavior
Methods

A key feature of objectoriented languages


Procedural languages, such as C, did not require clustering of data and behavior
Class/instance distinction
Class defines variables & methods
Need to create instanced of the class, called objects, to use variables & methods
Exception: static methods and variables
Analogy: a jelly bean mold (class) can be used to create a large number of jelly
beans (objects, instances of the class)

M. Romdhani, Janvier 2014

33

Inheritance
Operationally
If class B inherits from base class A, it gains all of the variables and
methods of A
Class B can optionally add more variables and methods
Class B can optionally change the methods of A
Uses
Reuse of class by specializing it for a specific context
Extending a general class for more specific uses
Interfaces
Allow reuse of method definitions of
interface
Subclass must implement method
definitions

M. Romdhani, Janvier 2014

34

17

Chapitre 1. Introduction C# et Visual Studio 2012

Inheritance Example
class A
{
public void display_one()
{
System.Console.WriteLine("I come from A");
}
}
class B : A
{
public void display_two()
{
System.Console.WriteLine("I come from B, child of A");
}
}
class App
{
static void Main()
{
A a = new A(); // Create instance of A
B b = new B(); // Create instance of B
a.display_one(); // I come from A
b.display_one(); // I come from A
b.display_two(); // I come from B, child of A
}
}

M. Romdhani, Janvier 2014

35

Visibility
A class is a container for data and behavior
Often want to control over which code:
Can read & write data
Can call methods

Access modifiers:
Public
No restrictions. Members visible to any method of any class

Private
Members in class A marked private only accessible to methods of class A
Default visibility of class variables (but is good to state this explicitly)

Protected
Members in class A marked protected accessible to methods of class A and subclasses of
A.

M. Romdhani, Janvier 2014

36

18

Chapitre 1. Introduction C# et Visual Studio 2012

Constructors
Use new to create a new object instance
This causes the constructor to be called
A constructor is a method called when an object is created
C# provides a default constructor for every class
Creates object but takes no other action

Typically classes have explicitly provided constructor


Constructor
Has same name as the class
Can take arguments
Usually public, though not always
Singleton design pattern makes constructor private to ensure only one object instance
is created

37

M. Romdhani, Janvier 2014

Predefined Types
C# predefined types
Reference object, string
Signed

sbyte, short, int, long

Unsigned byte, ushort, uint, ulong


Character char (2 byte, Unicode)
Floating-point

float, double, decimal

Logical

bool

Predefined types are simply aliases for system-provided types


For example, int == System.Int32
Unusual types in C#
Bool: Holds a boolean value: true or false
Decimal : A fixed precision number up to 28 digits plus decimal point
Useful for money calculations : 300.5m (Suffix m or M indicates decimal)

M. Romdhani, Janvier 2014

38

19

Chapitre 1. Introduction C# et Visual Studio 2012

Delegates
An objectified function
inherits from System.Delegate
sealed implicitly
looks much like C/C++ style function pointer
eg. delegate int Func(ref int x)
defines a new type: Func: takes int, returns int
declared like a function with an extra keyword
stores a list of methods to call
Example
delegate int Func(ref int x);
int Increment(ref int x) { return x++; }
int Decrement(ref int x) { return x--; }
Func F1 = new Func(Increment);
F1 += Decrement;
x = 10;
Console.WriteLine(F1(ref x));
Console.WriteLine(x);
39

M. Romdhani, Janvier 2014

Events
Special class of delegates
given the event keyword
class Room {
public event EventHandler Enter;
public void RegisterGuest(object source, EventArgs e) { }
public static void Main(string[] args) {
Enter += new EventHandler(RegisterGuest);
if (Enter != null) {
Enter(this, new EventArgs());
}
}
}

Enter is an object of type delegate

when event is raised each delegate called

C# allows any delegate to be attached to an event

.NET requires only EventHandlers


Adds restrictions to the delegate

can only raise an event in its defining class

outside, can only do += and -= : return void

M. Romdhani, Janvier 2014

40

20

Chapitre 1. Introduction C# et Visual Studio 2012

C# 3.0 Features
Implicitly Typed Local Variables
Extension Methods
Lambda Expressions
Object Initializers
Collection Initializers

41

M. Romdhani, Janvier 2014

Implicitly Typed Local Variables


Examples:
var
var
var
var
var

i = 5;
s = "Hello";
d = 1.0;
numbers = new int[] {1, 2, 3};
orders = new Dictionary<int,Order>();

Are equivalent to:


int i = 5;
string s = "Hello";
double d = 1.0;
int[] numbers = new int[] {1, 2, 3};
Dictionary<int,Order> orders = new Dictionary<int,Order>();

Errors:
var x;
var y = {1, 2, 3};
var z = null;

M. Romdhani, Janvier 2014

// Error, no initializer to infer type from


// Error, collection initializer not permitted
// Error, null type not permitted

42

21

Chapitre 1. Introduction C# et Visual Studio 2012

Extension Methods
Declaration:
public static partial class Extensions {
public static int ToInt32(this string s) {
return Int32.Parse(s);
}
}

Usage:
string s = "1234";
int i = s.ToInt32();

// Same as Extensions.ToInt32(s)

Instance methods take precedence over extension methods


Extension methods imported in inner namespace declarations take precedence
over extension methods imported in outer namespace declarations

M. Romdhani, Janvier 2014

43

Extension Methods (2)


Declaration:
public static partial class Extensions {
public static T[] Slice<T>(this T[] source, int index, int count) {
if (index < 0 || count < 0 || source.Length index < count)
throw new ArgumentException();
T[] result = new T[count];
Array.Copy(source, index, result, 0, count);
return result;
}
}

Usage:
int[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] a = digits.Slice(4, 3);
// Same as Extensions.Slice(digits, 4, 3)

M. Romdhani, Janvier 2014

44

22

Chapitre 1. Introduction C# et Visual Studio 2012

Lambda Expressions
Generalized function syntax
x.x+1
in C# 3.0, have x => x + 1
From anonymous delegate syntax:
delegate(int x) { return x + 1;}
Can have implicitly typed variables
Can have more than one variable
Can have expression or statement body
NB: no statement bodies in preview compiler

M. Romdhani, Janvier 2014

45

Lambda Expressions (2)


Can be converted to delegate type
if parameters and body match
delegate R Func<A,R>(A arg);
Func<int,int> f1 = x => x + 1;
Func<int,double> f2 = x => x + 1;
Func<double,int> f3 = x => x + 1;

Participate in type inference


If expression body, get expression trees

M. Romdhani, Janvier 2014

46

23

Chapitre 1. Introduction C# et Visual Studio 2012

Lambda Expressions (3)


Type inference
public static IEnumerable<S> Select<T,S>(
this IEnumerable<T> source,
Func<T,S> selector)
{
foreach (T element in source)
yield return selector(element);
}

If call Select(customers, c => c.Name);


T, S mapped to appropriate types

M. Romdhani, Janvier 2014

47

Object Initializers
Class representing a point:
public class Point {
private int x, y;

public int X { get { return x; } set { x = value; } }


public int Y { get { return y; } set { y = value; } }
}

New instance can be created using object initializer:


var a = new Point { X = 0, Y = 1 };

Which is equivalent to:


var a = new Point();
a.X = 0;
a.Y = 1;

M. Romdhani, Janvier 2014

48

24

Chapitre 1. Introduction C# et Visual Studio 2012

Object Initializers (2)


Class representing a rectangle:
public class Rectangle {
private Point p1, p2;
public Point P1 { get { return p1; } set { p1 = value; } }
public Point P2 { get { return p2; } set { p2 = value; } }
}

New instance can be created using object initializer:


var r = new Rectangle {
P1 = new Point { X = 0, Y = 1 },
P2 = new Point { X = 2, Y = 3 }
};

Which is equivalent to:


var r = new Rectangle();
var __p1 = new Point();
__p1.X = 0;
__p1.Y = 1;
r.P1 = __p1;
var __p2 = new Point();
__p2.X = 2;
__p2.Y = 3;
r.P2 = __p2;

M. Romdhani, Janvier 2014

49

Collection Initializers
Example:
List<int> digits = new List<int> { 0, 1, 2};

Is equivalent to:
List<int> digits = new List<int>();
digits.Add(0);
digits.Add(1);
digits.Add(2);

List<T> has to implement System.Collections.Generic.ICollection<T>


interface with the Add(T) method

M. Romdhani, Janvier 2014

50

25

Chapitre 1. Introduction C# et Visual Studio 2012

Auto-implemented Properties
Backed up by a private field normally inaccessible to programmer (only
via the property):
class LightweightCustomer {
public double TotalPurchases { get; set; }
public string Name { get; private set; }

// read-only

public int CustomerID { get; private set; }

// read-only

M. Romdhani, Janvier 2014

51

Anonymous Types
Following expression:
new { p1 = e1 , p2 = e2 , pn = en }

Can be used to define an anonymous type :


class __Anonymous1 {
private T1 f1 ;
private T2 f2 ;

private Tn fn ;
public T1 p1 { get { return f1 ; } set { f1 = value ; } }
public T2 p2 { get { return f2 ; } set { f2 = value ; } }

public T1 p1 { get { return f1 ; } set { f1 = value ; } }


}

And create its instance using object initializer


Different anonymous object initilizers that define properties with same
names in the same order generate the same anonymous type:
var p1 = new { Name = "Lawnmower", Price = 495.00 };
var p2 = new { Name = "Shovel", Price = 26.95 };
p1 = p2;
M. Romdhani, Janvier 2014

52

26

Chapitre 1. Introduction C# et Visual Studio 2012

Partial Methods
Can appear only in partial classes or structs, and must be void,
private and without out parameters:
partial class A {
string _name;
partial void OnNameChanged();
public string Name {
set {
_name = value;
OnNameChanged();
}
}
}
partial class A {
partial void OnNameChanged() {
// Do something
}
}

53

M. Romdhani, Janvier 2014

LINQ to Objects
Set of generic extension methods (Select, Where, OrderBy, + others)
implemented for IEnumerable<T> interface, example:
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numberGroups = from n in numbers group n by n % 5 into g
select new {Remainder = g.Key, Numbers = g.Group};
foreach (var g in numberGroups) {
Console.WriteLine(
"Numbers with a remainder of {0} when divided by 5:", g.Remainder);
);
foreach (int n in g.Numbers) {
Console.WriteLine(n);
}
}

LINQ to SQL Classes for SQL data access using


query expressions
LINQ to XML - Classes for XML data access using
query expressions
LINQ to DataSets - Classes for querying Datasets using
query expressions (on typed DataSets works similarly
as LINQ to SQL)
M. Romdhani, Janvier 2014

Numbers with a remainder of 0 when divided by 5:


5
0
Numbers with a remainder of 4 when divided by 5:
4
9
Numbers with a remainder of 1 when divided by 5:
1
6
Numbers with a remainder of 3 when divided by 5:
3
8
Numbers with a remainder of 2 when divided by 5:
7
2

54

27

Chapitre 1. Introduction C# et Visual Studio 2012

C# 4.0 Features
Dynamic Typed objects
Named and optional Parameters

55

M. Romdhani, Janvier 2014

Dynamic Typed Objects


Calculator calc = GetCalculator();
int sum = calc.Add(10, 20);
object calc = GetCalculator();
Type calcType = calc.GetType();
object res = calcType.InvokeMember("Add",
BindingFlags.InvokeMethod, null,
new object[] { 10, 20 });
ScriptObject calc = GetCalculator();
int sum = Convert.ToInt32(res);
object res = calc.Invoke("Add", 10, 20);
int sum = Convert.ToInt32(res);

Statically typed
to be dynamic

dynamic calc = GetCalculator();


int sum = calc.Add(10, 20);

Dynamic
conversion
M. Romdhani, Janvier 2014

Dynamic method
invocation
56

28

Chapitre 1. Introduction C# et Visual Studio 2012

Named and Optional Parameters


Consider this example:

public void M(int x, int y = 5, int z = 7) { }


In this method, the parameters y and z are assigned default values.
Calls to this method might look like this:
M(1, 2, 3); // ordinary call of M
M(1, 2); // omitting z equivalent to M(1, 2, 7)
M(1); // omitting both y and z equivalent to M(1, 5, 7)
M(1, z: 3); // passing z by name
M(x: 1, z: 3); // passing both x and z by name
M(z: 3, x: 1); // reversing the order of arguments

M. Romdhani, Janvier 2014

57

Covariance & Contravariance


If the type of the return value is subclass
then the delegate is still acceptable
called covariance
If the type of the args are subclasses
then the delegate is likewise acceptable
called contravariance

M. Romdhani, Janvier 2014

58

29

Chapitre 1. Introduction C# et Visual Studio 2012

Generic co- and contravariance


If T appears only as an output, its safe to pass
X<TDerived> for X<T>
We call this covariance
C# uses the syntax X<out T>

If T appears only as an input, its safe to pass


X<TBase> for X<T>
We call this contravariance
C# uses the syntax X<in T>

M. Romdhani, Janvier 2014

59

Variance en .NET 4.0


Interfaces
System.Collections.Generic.IEnumerable<out T>
System.Collections.Generic.IEnumerator<out T>
System.Linq.IQueryable<out T>
System.Collections.Generic.IComparer<in T>
System.Collections.Generic.IEqualityComparer<in T>
System.IComparable<in T>

Delegates
System.Func<in T, , out R>
System.Action<in T, >
System.Predicate<in T>
System.Comparison<in T>
System.EventHandler<in T>
M. Romdhani, Janvier 2014

60

30

Vous aimerez peut-être aussi