Upload
aymen-bokri
View
232
Download
0
Embed Size (px)
Citation preview
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
1/30
1
Chapitre 1. Introduction à C# et à Visual Studio 2012
Chapitre 1
Introduction au .NET Framework,à Visual Studio 2012,
et au langage C#
Mohamed RomdhaniMCSD Web Applicatio ns .NET 4.5
2M . Rom dh a n i , J a n v i e r 2 0 1 4
Contenu
Le .NET Framework
Présentation de Visual Studio
Introduction au langage C#
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
2/30
2
Chapitre 1. Introduction à C# et à Visual Studio 2012
3M . Rom dh a n i , J a n v i e r 2 0 1 4
Le .NET Framework
4M . Rom dh a n i , J a n v i e r 2 0 1 4
Qu’est ce que .NET ?
Un Modèle de programmation uni fié
Une plate-forme de déplo iement et d’exécution
Framework .NET : Gratuit & intégré à Windows
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
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
3/30
3
Chapitre 1. Introduction à C# et à Visual Studio 2012
5M . Rom dh a n i , J a n v i e r 2 0 1 4
Architecture
OS
.NET Framework
Application
6M . Rom dh a n i , J a n v i e r 2 0 1 4
Components of the Framework
V i s
u a l S t u d i o
Common Language Runtime Assembly load and execution
Base Class LibraryCore types and services
Frameworks
ASP.NET WinForms WPF WCF etc.
Languages
VB C#Ruby /
Pythonetc.
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
4/30
4
Chapitre 1. Introduction à C# et à Visual Studio 2012
7M . Rom dh a n i , J a n v i e r 2 0 1 4
Historique du .NET Frameworket 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
8M . Rom dh a n i , J a n v i e r 2 0 1 4
Historique d’évolution de la CLR
.NET 1.0 .NET 1.1 .NET 2.0
3.0
3.5
.NET 4
2002 2003 2008 CTP!2005-08
CLR 1.0CLR
1.1 CLR 2.0CLR 4
SP1
.NET 4
2008 CTP!
CLR 4.5
4.5
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
5/30
5
Chapitre 1. Introduction à C# et à Visual Studio 2012
9M . Rom dh a n i , J a n v i e r 2 0 1 4
Caractéristiques de la plateforme.Net
Les langages génèrentdésormais un langagecommun, basé sur des typescommuns : le MSIL(Microsoft IntermediateLanguage)
Ces modules en MSIL sontcompi lés en code machine àla volée (« just in time »)
Astuce : i l es t possible delire le MSIL avec i ldasm
Astuce : i l es t possible dedécompil er avec reflector
10M . Rom dh a n i , J a n v i e r 2 0 1 4
Common Language Runtime ( C LR )
Common Type System
JIT (just-in-time) Compiler
Code access security
Garbage Collection
Class Loader
COM Interoperability
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
6/30
6
Chapitre 1. Introduction à C# et à Visual Studio 2012
11M . Rom dh a n i , J a n v i e r 2 0 1 4
JIT Compilation and Runtime
SourceCode
.cs
Compiler
.exe
MSIL
MSIL
containing
.NET
Assembly
JIT’ter
Enter TitleHere
csc.exe
(Compile time)
Run time
CLR
Memory
12M . Rom dh a n i , J a n v i e r 2 0 1 4
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)
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
7/30
7
Chapitre 1. Introduction à C# et à Visual Studio 2012
13M . Rom dh a n i , J a n v i e r 2 0 1 4
What does MS I L look like?
ILDASM.exe
14M . Rom dh a n i , J a n v i e r 2 0 1 4
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 definesSystem.Int324 byte integer
C# defines int as analias of System.Int32
Value Types areallocated on the Stack
Reference Types areallocated on the Heap
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
8/30
8
Chapitre 1. Introduction à C# et à Visual Studio 2012
15M . Rom dh a n i , J a n v i e r 2 0 1 4
What is an assembly ?
MyAssembly .dll OR .exe
Building blocks of .NET Framework applications
Collection of types and resources that form a logical unit of functionality
MyClassA
MyClassB
MyResource
V 1 . 1 . 2 5 4 . 1
Assembly version< m a j o r > . < m i n o r > . < b u i l d > . < r e v is io n >
Assembly signedwith a digitalcertificate
16M . Rom dh a n i , J a n v i e r 2 0 1 4
Organisation du Framework .NET
System
System.IO
Entrées/Sorties
System.Security
System.Collections
Listes, tableaux, etc….
System.Resources
Traduction automatique
System.Text
StringBuilder
System.Text.RegularExpressions
System.Configuration
Accès aux fichiers de config XML.
System.Xml
System.Xml.Schema
Pour les XSD
System.Xml.Serialization
Transformation d’un objet en XML etinversement.
System.Xml.XPath
Parcours optimisé d’un flux XML.
System.Xml.Xsl
Transformation XSLT : formatage
d’un flux XML.
System.Data
ADO.NET
System.Data.OracleClient
Se trouve dans une assemblydistincte.
System.Data.Sql
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
9/30
9
Chapitre 1. Introduction à C# et à Visual Studio 2012
17M . Rom dh a n i , J a n v i e r 2 0 1 4
What Tools Does the .NET FrameworkProvide?
Makecert.exeCaspol.exe
Gacutil.exeNgen.exe
Ildasm.exe Sn.exe
18M . Rom dh a n i , J a n v i e r 2 0 1 4
Présentation de Visual Studio
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
10/30
10
Chapitre 1. Introduction à C# et à Visual Studio 2012
19M . Rom dh a n i , J a n v i e r 2 0 1 4
Visual Studio 2012:
Intuitive IDE that enables developers to quickly buildapplications in their chosen programming language
Visual Studio 2012 features:
Rapid application developmentServer and data access
Debugging featuresError handlingHelp and documentation
Visual Studio 2012 IDE Overview
20M . Rom dh a n i , J a n v i e r 2 0 1 4
Integrated Development Environment (IDE) Project templates
Wizards
Debugging
IntelliSense
Visual Studio 2012 IDE Overview
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
11/30
11
Chapitre 1. Introduction à C# et à Visual Studio 2012
21M . Rom dh a n i , J a n v i e r 2 0 1 4
The Structure of Visual Studio Projects andSolutions
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
.aspx
.aspx.cs .config
.csproj
WPF project
.xaml
.xaml.cs .config
.csproj
Console project
.cs
.config
.csproj
22M . Rom dh a n i , J a n v i e r 2 0 1 4
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)
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
12/30
12
Chapitre 1. Introduction à C# et à Visual Studio 2012
23M . Rom dh a n i , J a n v i e r 2 0 1 4
Visual Studio 2012 IDE Overview (cont.)
Menu in the menu bar Solution Explorer window
Form (WindowsForms a pplication)
Properties
window
24M . Rom dh a n i , J a n v i e r 2 0 1 4
Menu Bar and Toolbar
The set of m enus displayed depends on what you are currently doin g in the IDE
You can access common commands from the toolbar icons
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
13/30
13
Chapitre 1. Introduction à C# et à Visual Studio 2012
25M . Rom dh a n i , J a n v i e r 2 0 1 4
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 For mat (Ctr l +K, D or Ctr l +E, D)
Surround With (Ctrl +S) Surrounds a block of code with a code snippet.
26M . Rom dh a n i , J a n v i e r 2 0 1 4
Introduction au langage C#
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
14/30
14
Chapitre 1. Introduction à C# et à Visual Studio 2012
27M . Rom dh a n i , J a n v i e r 2 0 1 4
Purpose of C#
C# has been standardized and is described by the ECMA-334 C# Language Specification
C# uses a very similar syntax to C, C++, and Java
C# is the language of choice for many developers who build.NET Framework applications
C#
28M . Rom dh a n i , J a n v i e r 2 0 1 4
C# au fil de l’histoire …
[http://jlambert.developpez.com/tutoriels/dotnet/nouveautes-csharp-5/]
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
15/30
15
Chapitre 1. Introduction à C# et à Visual Studio 2012
29M . Rom dh a n i , J a n v i e r 2 0 1 4
The Structure of a Console Application
usi ng Syst em;
namespace MyFi r s t Appl i ca t i on
{c l ass Pr ogr am
{
s t at i c v oi d Mai n( s t r i ng[ ] ar gs )
{
}
}
}
Bring System namespace into scope
Program class declaration
Main method declaration
Namespace declaration
30M . Rom dh a n i , J a n v i e r 2 0 1 4
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
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
16/30
16
Chapitre 1. Introduction à C# et à Visual Studio 2012
31M . Rom dh a n i , J a n v i e r 2 0 1 4
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 nocurrent instance of the class. It’s a class method, not an instance method.
The line beginning with // is a comment, and does not execute.
32M . Rom dh a n i , J a n v i e r 2 0 1 4
Syntax
Case-sensitive
Whitespace has no meaning
Sequences of space, tab, linefeed, carriage return
Semico lons are used to t erminate statements (;)
Curly braces {} enclose code blocks
Comments:
/* comment */
// comment
///
Automatic XML commenting facility
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
17/30
17
Chapitre 1. Introduction à C# et à Visual Studio 2012
33M . Rom dh a n i , J a n v i e r 2 0 1 4
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 jellybeans (objects, instances of the class)
34M . Rom dh a n i , J a n v i e r 2 0 1 4
Inheritance
Operationally
If class B inherits from base class A, it gains all of the variables andmethods 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 ofinterface
Subclass must implement methoddefinitions
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
18/30
18
Chapitre 1. Introduction à C# et à Visual Studio 2012
35M . Rom dh a n i , J a n v i e r 2 0 1 4
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
}
}
36M . Rom dh a n i , J a n v i e r 2 0 1 4
Visibility
A class is a container for data and behavior
Often want to cont rol over which code:
Can read & write data
Can call methods
Access modif ier s: 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.
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
19/30
19
Chapitre 1. Introduction à C# et à Visual Studio 2012
37M . Rom dh a n i , J a n v i e r 2 0 1 4
Constructors
Use “ new” to create a new object instance
This causes the “constructor” to be called
A const ructor is a method called when an ob ject 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 instanceis created
38M . Rom dh a n i , J a n v i e r 2 0 1 4
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 f loat, 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)
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
20/30
20
Chapitre 1. Introduction à C# et à Visual Studio 2012
39M . Rom dh a n i , J a n v i e r 2 0 1 4
Delegates
An object if ied functi on
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);
40M . Rom dh a n i , J a n v i e r 2 0 1 4
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
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
21/30
21
Chapitre 1. Introduction à C# et à Visual Studio 2012
41M . Rom dh a n i , J a n v i e r 2 0 1 4
C# 3.0 Features
Implici tly Typed Local Variables
Extension Methods
Lambda Expressions
Object Initiali zers
Collection Initi alizers
42M . Rom dh a n i , J a n v i e r 2 0 1 4
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();
Are equivalen t to:
int i = 5;string s = "Hello";
double d = 1.0;
int[] numbers = new int[] {1, 2, 3};
Dictionary orders = new Dictionary();
Errors:
var x; // Error, no initializer to infer type from
var y = {1, 2, 3}; // Error, collection initializer not permitted
var z = null; // Error, null type not permitted
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
22/30
22
Chapitre 1. Introduction à C# et à Visual Studio 2012
43M . Rom dh a n i , J a n v i e r 2 0 1 4
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 Extensi ons.ToInt32(s)
Instance methods take precedence over extension methods
Extension methods imported in inner namespace declarations take precedenceover extension methods impor ted in outer namespace declarations
44M . Rom dh a n i , J a n v i e r 2 0 1 4
Extension Methods (2)
Declaration:
public static partial class Extensions { public static T[] Slice(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 Extensio ns.Slice(dig its, 4, 3)
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
23/30
23
Chapitre 1. Introduction à C# et à Visual Studio 2012
45M . Rom dh a n i , J a n v i e r 2 0 1 4
Lambda Expressions
Generalized function syntax
x . x + 1
in C# 3.0, have x => x + 1
From anonymous delegate syntax:
del egat e( i nt x) { r et ur n x + 1; }
Can have impl icitl y typed variables
Can have more than one variable
Can have expression or statement body
NB: no statement bodies in preview compiler
46M . Rom dh a n i , J a n v i e r 2 0 1 4
Lambda Expressions (2)
Can be converted to delegate type
if parameters and body match
del egat e R Func( A ar g) ;Func f 1 = x => x + 1;Func f 2 = x => x + 1;Func f 3 = x => x + 1;
Participate in type inference
If expression body, get expression trees
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
24/30
24
Chapitre 1. Introduction à C# et à Visual Studio 2012
47M . Rom dh a n i , J a n v i e r 2 0 1 4
Lambda Expressions (3)
Type inference public static IEnumerable Select(
this IEnumerable source,
Func selector)
{
foreach (T element in source)
yield return selector(element);
}
If call Sel ect ( cust omers, c => c. Name) ;
T, S mapped to appropriate types
48M . Rom dh a n i , J a n v i e r 2 0 1 4
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 obj ect init ializer:
var a = new Point { X = 0, Y = 1 };
Which is equivalent to:
var a = new Poi nt( );
a.X = 0;
a. Y = 1;
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
25/30
25
Chapitre 1. Introduction à C# et à Visual Studio 2012
49M . Rom dh a n i , J a n v i e r 2 0 1 4
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 obj ect init ializer: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;
50M . Rom dh a n i , J a n v i e r 2 0 1 4
Collection Initializers
Example:
List digits = new List { 0, 1, 2};
Is equivalent to:
List digits = new List();
digits.Add(0);
digits.Add(1);digits.Add(2);
List has to implement System.Collections.Generic.ICollectioninterface with the Add(T) method
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
26/30
26
Chapitre 1. Introduction à C# et à Visual Studio 2012
51M . Rom dh a n i , J a n v i e r 2 0 1 4
Auto-implemented Properties
Backed up by a private field normally inaccessible to programmer (onlyvia 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
}
52M . Rom dh a n i , J a n v i e r 2 0 1 4
Anonymous Types
Following expression:new { p1 = e1 , p2 = e2 , … pn = en }
Can be used to define an anonymous t ype :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 usi ng object in it ial izer
Different anonymous object init ili zers that define properties with samenames 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;
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
27/30
27
Chapitre 1. Introduction à C# et à Visual Studio 2012
53M . Rom dh a n i , J a n v i e r 2 0 1 4
Partial Methods
Can appear only in parti al classes or struct s, 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
}}
54M . Rom dh a n i , J a n v i e r 2 0 1 4
LINQ to Objects
Set o f generic extension m ethods (Select, Where, OrderBy, … + o thers)imp lemented for IEnumerable interface, example:
i nt[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numberGr oups = from n in number s group n by n %5 into g
select new {Remai nder = g.Key, Numbers = g.Group};
f oreach ( var g i n numberGr oups) {
Consol e.Wri t eLi ne(
"Number s wi t h a remai nder of {0} when di vi ded by 5: " , g. Remai nder ) ;
) ;
f oreach (i nt n i n g. Numbers ) {
Consol e.Wri t eLi ne( n);
}
}
LINQ to SQL – Classes for SQL data access usingquery expressions
LINQ to XML - Classes fo r XML data access usingquery expressions
LINQ to DataSets - Classes for querying Datasets usingquery expressions (on typed DataSets works s imilarlyas LINQ to SQL)
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
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
28/30
28
Chapitre 1. Introduction à C# et à Visual Studio 2012
55M . Rom dh a n i , J a n v i e r 2 0 1 4
C# 4.0 Features
Dynamic Typed ob jects
Named and optional Parameters
56M . Rom dh a n i , J a n v i e r 2 0 1 4
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 });
int sum = Convert.ToInt32(res);ScriptObject calc = GetCalculator();
object res = calc.Invoke("Add", 10, 20);
int sum = Convert.ToInt32(res);
dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);
Statically typed
to be dynamic
Dynamic method
invocation
Dynamic
conversion
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
29/30
29
Chapitre 1. Introduction à C# et à Visual Studio 2012
57M . Rom dh a n i , J a n v i e r 2 0 1 4
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 thi s 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
58M . Rom dh a n i , J a n v i e r 2 0 1 4
Covariance & Contravariance
If the type of the return value is subclass
then the delegate is still acceptable
called covariance
If the type of t he args are subclasses
then the delegate is likewise acceptable
called contravariance
8/17/2019 2015. GL3. ProgrammationII. Chap1. Introduction à .NET Framework Et à C#
30/30
Chapitre 1. Introduction à C# et à Visual Studio 2012
59M . Rom dh a n i , J a n v i e r 2 0 1 4
Generic co- and contravariance
If T appears only as an output, it ’s safe to passX fo r X
We call this covariance
C# uses the syntax X
If T appears only as an input, it’s safe to passX for X
We call this contravariance
C# uses the syntax X
60M . Rom dh a n i , J a n v i e r 2 0 1 4
Variance en .NET 4.0
System.Collections.Generic.IEnumerable
System.Collections.Generic.IEnumerator
System.Linq.IQueryable
System.Collections.Generic.IComparer
System.Collections.Generic.IEqualityComparerSystem.IComparable
System.Func
System.Action
System.Predicate
System.Comparison
System.EventHandler
Interfaces
Delegates