these slides are the main code samples I am using to introduce Object Oriented programming features of C# : initializers, anonymous types, extension methods, delegates, lambda & Linq
Anonymous Types
var variableTypeAnonyme = new { FirstName = "Flavien", Age = 23};
var variableTypeAnonyme = new { DateOfBirth = new DateTime(1984, 11, 15) };
var variableTypeAnonyme = 12;
var variableTypeAnonyme = "Flavien";
Extension methods
public static class Encodage
{
public static string Crypte(string chaine)
{
return
Convert.ToBase64String(Encoding.Default.GetBytes(chaine));
}
public static string Decrypte(string chaine)
{
return
Encoding.Default.GetString(Convert.FromBase64String(chaine));
}
}
public class TrieurDeTableau
{
[…Code supprimé pour plus de clarté…]
public void DemoTri(int[] tableau)
{
DelegateTri tri = TriAscendant;
tri(tableau);
//affichage
tri = TriDescendant;
tri(tableau);
//affichage
}}
Using delegates
static void Main(string[] args)
{
int[] tableau = new int[] { 4, 1,10, 8, 5 };
new TrieurDeTableau().DemoTri(tableau);
}
Delegate to lambda
DelegateTri tri = delegate(int[] leTableau)
{
Array.Sort(leTableau);
};
DelegateTri tri = (leTableau) =>
{
Array.Sort(leTableau);
};
Lambda
List<int> list = new List<int>(new int[] { 2, -5, 45, 5 });
var positiveNumbers = list.FindAll((int i) => i > 0);
LINQ
From source
Where condition
Select variable
LINQ
class IntroToLINQ{
static void Main()
{
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}}}
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
var evenNumQuery =
from num in numbers
where (num % 2) == 0
select num;
int evenNumCount = evenNumQuery.Count();
List<int> numQuery2 =
(from num in numbers
where (num % 2) == 0
select num).ToList();
// or like this:
// numQuery3 is still an int[]
var numQuery3 =
(from num in numbers
where (num % 2) == 0
select num).ToArray();