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

Chapitre 1

Introduction au .NET Framework, à Visual Studio 2012, et au langage C#

1 Introduction au .NET Framework, à Visual Studio 2012, et au langage C# Mohamed Romdhani MCSD
1 Introduction au .NET Framework, à Visual Studio 2012, et au langage C# Mohamed Romdhani MCSD

Mohamed Romdhani

MCSD Web Applications .NET 4.5

1 Introduction au .NET Framework, à Visual Studio 2012, et au langage C# Mohamed Romdhani MCSD

Contenu

Le .NET Framework

Présentation de Visual Studio

Introduction au langage C#

M. Romdhani, Janvier 2014

2

Chapitre 1. Introduction à C# et à Visual Studio 2012

3

Le .NET Framework

M. Romdhani, Janvier 2014

Qu’est ce que .NET ?

Définition : [dot-net] .NET est une plateforme complète pour développer, déployer et exécuter des Applications
Définition : [dot-net]
.NET est une plateforme
complète pour développer,
déployer et exécuter des
Applications Web, Windows,
Mobiles et serveur
des Applications Web, Windows, Mobiles et serveur  Un Modèle de programmation unifié  Une

Un Modèle de programmation unifié

Une plate-forme de déploiement et d’exécution

Framework .NET : Gratuit & intégré à Windows

M. Romdhani, Janvier 2014

4

Chapitre 1. Introduction à C# et à Visual Studio 2012

Architecture

Application
Application
.NET Framework
.NET Framework
OS
OS

M. Romdhani, Janvier 2014

5

Visual Studio Components of the Framework Frameworks Languages Ruby / ASP.NET WinForms WPF WCF etc.
Visual Studio
Components of the Framework
Frameworks
Languages
Ruby /
ASP.NET
WinForms
WPF
WCF
etc.
VB
C#
etc.
Python
Base Class Library
Core types and services
Common Language Runtime
Assembly load and execution
6
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

7

Historique d’évolution de la CLR

 
.NET 1.0
.NET 1.0
.NET 1.1
.NET 1.1
SP1 3.5 3.0 .NET 2.0
SP1
3.5
3.0
.NET 2.0
.NET 4
.NET 4
4.5 .NET 4
4.5
.NET 4
 

2002

2003

2005-08

2008 CTP!

2008 CTP!

CLR 1.0
CLR 1.0
CLR 1.1
CLR
1.1
CLR 2.0
CLR 2.0
CLR 4
CLR 4
CLR 4.5
CLR 4.5

M.

Romdhani, Janvier 2014

 

8

Chapitre 1. Introduction à C# et à Visual Studio 2012

 

Caractéristiques de la plateforme .Net

 
 

Les langages génèrent désormais un langage commun, basé sur des types communs : le MSIL (Microsoft Intermediate Language)

génèrent désormais un langage commun, basé sur des types communs : le MSIL (Microsoft Intermediate Language)
 

Ces modules en MSIL sont compilés en code machine à la volée (« just in time »)

Astuce : il est possible de lire le MSIL avec ildasm

Astuce : il est possible de décompiler avec reflector

M.

Romdhani, Janvier 2014

9

 

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 MSIL Code Compiler containing .cs csc.exe MSIL .NET (Compile
JIT Compilation and Runtime
.exe
Source
MSIL
Code
Compiler
containing
.cs
csc.exe
MSIL
.NET
(Compile time)
Assembly
Run time
JIT’ter
CLR
Enter Title Here
Memory
11
M.
Romdhani, Janvier 2014

MSIL

 

.NET Languages JIT’ting 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 13 M. Romdhani, Janvier 2014
What does MSIL look like?
 ILDASM.exe
13
M.
Romdhani, Janvier 2014
What is the Common Type System?  A set of common types  any language
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
14
M.
Romdhani, Janvier 2014

Chapitre 1. Introduction à C# et à Visual Studio 2012

What is an assembly ?

Building blocks of .NET Framework applications
Building blocks of .NET Framework applications

Collection of types and resources that form a logical unit of functionality

MyAssembly .dll OR .exe
MyAssembly .dll OR .exe

MyClassA

MyResource

Assembly signed with a digital certificate

MyClassB

V 1.1.254.1

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

M.

Romdhani, Janvier 2014

15

M. Romdhani, Janvier 2014 15 Organisation du Framework .NET  System 

Organisation du Framework .NET

System

System.Xml.Serialization

System.IO

Transformation d’un objet en XML et inversement.

Entrées/Sorties

System.Security

System.Xml.XPath

Parcours optimisé d’un flux XML.

System.Collections

Listes, tableaux, etc….

System.Xml.Xsl

System.Resources

Transformation XSLT : formatage d’un flux XML.

Traduction automatique

System.Text

System.Data

StringBuilder

ADO.NET

System.Text.RegularExpressions

System.Configuration

System.Data.OracleClient

Accès aux fichiers de config XML.

Se trouve dans une assembly distincte.

System.Xml

System.Data.Sql

System.Xml.Schema

Pour les XSD

M.

Romdhani, Janvier 2014

16

Chapitre 1. Introduction à C# et à Visual Studio 2012

What Tools Does the .NET Framework Provide?

 
 
   
 
   

Caspol.exe

Makecert.exe

 
      Caspol.exe Makecert.exe   Ngen.exe Gacutil.exe   Ildasm.exe S n . e x
      Caspol.exe Makecert.exe   Ngen.exe Gacutil.exe   Ildasm.exe S n . e x
      Caspol.exe Makecert.exe   Ngen.exe Gacutil.exe   Ildasm.exe S n . e x

Ngen.exe

Gacutil.exe

 
Makecert.exe   Ngen.exe Gacutil.exe   Ildasm.exe S n . e x e M. Romdhani, Janvier 2014
Makecert.exe   Ngen.exe Gacutil.exe   Ildasm.exe S n . e x e M. Romdhani, Janvier 2014
Makecert.exe   Ngen.exe Gacutil.exe   Ildasm.exe S n . e x e M. Romdhani, Janvier 2014
Makecert.exe   Ngen.exe Gacutil.exe   Ildasm.exe S n . e x e M. Romdhani, Janvier 2014

Ildasm.exe

Sn.exe

M.

Romdhani, Janvier 2014

 

17

 

Présentation 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
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
19
M.
Romdhani, Janvier 2014
Visual Studio 2012 IDE Overview
Integrated Development Environment (IDE)
 Project templates
 Wizards
 Debugging
 IntelliSense
20
M.
Romdhani, Janvier 2014

Chapitre 1. Introduction à C# et à Visual Studio 2012

The Structure of Visual Studio Projects and Solutions Visual Studio Solution Visual Studio solutions are
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
.csproj
.xaml
.csproj
.aspx.cs .config
.xaml.cs .config
Console project
.cs
.csproj
.config
21
M.
Romdhani, Janvier 2014
Visual Studio 2012 IDE Overview
Visual Basic Windows Forms Application
(selected)
Default project name
(provided by Visual Studio)
Description of
selected project
(provided by Visual Studio)
22
M.
Romdhani, Janvier 2014

Chapitre 1. Introduction à C# et à Visual Studio 2012

Visual Studio 2012 IDE Overview (cont.) Menu in the menu bar Solution Explorer window Form
Visual Studio 2012 IDE Overview (cont.)
Menu in the menu bar
Solution Explorer window
Form (Windows
Forms application)
Properties
window
23
M.
Romdhani, Janvier 2014
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
24
M.
Romdhani, Janvier 2014

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

Chapitre 1. Introduction à C# et à Visual Studio 2012

Purpose of C# C# C# is the language of choice for many developers who build
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 ECMA-
334 C# Language Specification
27
M.
Romdhani, Janvier 2014
C# au fil de l’histoire … [http://jlambert.developpez.com/tutoriels/dotnet/nouveautes-csharp-5/] 28 M. Romdhani,
C# au fil de l’histoire …
[http://jlambert.developpez.com/tutoriels/dotnet/nouveautes-csharp-5/]
28
M.
Romdhani, Janvier 2014

Chapitre 1. Introduction à C# et à Visual Studio 2012

The Structure of a Console Application

Bring System namespace into scope
Bring System namespace into scope

using System;

namespace MyFirstApplication

{

Namespace declaration

class Program

{

Program class declaration

static void Main(string[] args)

{

}

}

Main method declaration

}

M.

Romdhani, Janvier 2014

29

method declaration } M. Romdhani, Janvier 2014 29 Key language features  Unified object system 

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

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. It’s 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

Chapitre 1. Introduction à C# et à Visual Studio 2012

 

Classes and Objects

 
 

A class combines together

 

Data

 
 

Class variables

 

Behavior

 

Methods

 

A key feature of object- oriented 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

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 // I come from A // I come from B, child of A

 

b.display_one();

b.display_two();

 

}

}

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

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

M.

Romdhani, Janvier 2014

37

 

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

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);

 

M.

Romdhani, Janvier 2014

 

39

 

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

Chapitre 1. Introduction à C# et à Visual Studio 2012

 

C# 3.0 Features

 
 

Implicitly Typed Local Variables

 

Extension Methods

 

Lambda Expressions

 

Object Initializers

 

Collection Initializers

 

M.

Romdhani, Janvier 2014

 

41

 

Implicitly Typed Local Variables

 
 

Examples:

 

var i = 5; var s = "Hello"; var d = 1.0; var numbers = new int[] {1, 2, 3}; var 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:

 
 

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

var

// Error, no initializer to infer type from // Error, collection initializer not permitted // Error, null type not permitted

M.

Romdhani, Janvier 2014

 

42

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

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

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

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

= new Point(); = 0; = 1;

p1

p1.X

p1.Y

r.P1 =

p1;

var

= new Point(); = 2; = 3;

p2

p2.X

p2.Y

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

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

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

 
 

}

 

}

M.

Romdhani, Janvier 2014

53

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

Chapitre 1. Introduction à C# et à Visual Studio 2012

C# 4.0 Features  Dynamic Typed objects  Named and optional Parameters 55 M. Romdhani,
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 });
Convert.ToInt32(res); ScriptObject calc = GetCalculator();
int sum =
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
Dynamic method
conversion
invocation
56
M.
Romdhani, Janvier 2014

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

Chapitre 1. Introduction à C# et à Visual Studio 2012

Generic co- and contravariance  If T appears only as an output, it’s safe to
Generic co- and contravariance
 If T appears only as an output, it’s 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, it’s safe to pass
X<TBase> for X<T>
 We call this contravariance
 C# uses the syntax X<in T>
59
M.
Romdhani, Janvier 2014
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>
60
M.
Romdhani, Janvier 2014