whats new in_csharp4
TRANSCRIPT
What’s New in C# 4.0
Abed El-Azeem Bukhari (MCPD,MCTS,MCP)el-bukhari.com
private int test;public int Test{get {return test}set {test = value;}}
public int MyProperty { get; set; }
Short-form Properties
What’s new in C# 3.5?
Object and collection Initializepublic class MyStructure{public int MyProperty1 { get; set; }public int MyProperty2 { get; set; }}
MyStructure myStructure = new MyStructure() { MyProperty1 = 5,MyProperty2 = 10 };
List < int > myInts = new List < int > () { 5, 10, 15, 20, 25 };
What’s new in C# 3.5?
What’s new in C# 4.0
public void Myfunction( string param1=“flykit", bool param2 = false, int param3 = 24 ){ }
As VB.NET, You can put default values for the parameters.
Optional Parameters
Named Parameters
Myfunction(“najah",50); // Error !
Myfunction(“najah",param3: 50);
public void Myfunction( string param1=“flykit", bool param2 = false, int param3 = 24 ){ }
COM interop
((Excel.Range)excel.Cells[1, 1]).Value = “Hiiiiiiiii";
excel.Cells[1, 1].Value = "Hiiiiiiiii";
Variance
IList<string> strings = new List<string>();IList<object> objects = strings;//Error
IEnumerable<object> objects = strings;
Dynamic Programming
object calculator = GetCalculator(); Type calculatorType = calculator.GetType(); object res = calculatorType.InvokeMember("Add", BindingFlags.InvokeMethod, null, calculator, new object[] { 10, 20 }); int sum = Convert.ToInt32(res);
And what if the calculator was a JavaScript object?ScriptObject calculator = GetCalculator(); object res = calculator.Invoke("Add", 10, 20); int sum = Convert.ToInt32(res); For each dynamic domain we have a different programming experience and that makes it very hard to unify the code.
With C# 4.0 it becomes possible to write code this way:dynamic calculator = GetCalculator(); int sum = calculator.Add(10, 20);
Dynamic Programming cont.dynamic x = 1; dynamic y = "Hello"; dynamic z = new List<int> { 1, 2, 3 };
Code Resolution Method
double x = 1.75;double y = Math.Abs(x);
compile-time double Abs(double x)
dynamic x = 1.75;dynamic y = Math.Abs(x);
run-time double Abs(double x)
dynamic x = 2;dynamic y = Math.Abs(x);
run-time int Abs(int x)
Diffrence between var and dynamic keyword:
string s = “We are DotNet Students";var test = s; Console.WriteLine(test.MethodDoesnotExist());// Error
'string' does not contain a definition for 'MethodDoesnotExist' and no extension method 'MethodDoesnotExist'
string s = “We are DotNet Students";dynamic test = s;Console.WriteLine(test.MethodDoesnotExist());//OK!
Used for programming with COM or JavaScript which can have runtime properties!!
System.Tuple
var squaresList = System.Tuple.Create(1, 4, 9, 16, 25, 36, 49, 64); Console.WriteLine("1st item: {0}", squaresList.Item1); //1 Console.WriteLine("4th item: {0}", squaresList.Item4); //16 Console.WriteLine("8th item: {0}", squaresList.Rest); //(64)Console.ReadKey(); Console.WriteLine(Environment.NewLine);
System.Tuple cont. var tupleWithMoreThan8Elements = System.Tuple.Create("is", 2.3, 4.0f, new List<CHAR> { 'e', 't', 'h' }, “najah dotnet", new Stack<INT>(4), "best", squaresList);
// we'll sort the list of chars in descending order tupleWithMoreThan8Elements.Item4.Sort(); tupleWithMoreThan8Elements.Item4.Reverse(); Console.WriteLine("{0} {1} {2} {3}", tupleWithMoreThan8Elements.Item5, tupleWithMoreThan8Elements.Item1, string.Concat(tupleWithMoreThan8Elements.Item4), tupleWithMoreThan8Elements.Item7); // najah dotnet is the best
Console.WriteLine("Rest: {0}", tupleWithMoreThan8Elements.Rest); Console.WriteLine("Rest's 2nd element: {0}", tupleWithMoreThan8Elements.Rest.Item1.Item2); Console.WriteLine("Rest's 5th element: {0}", tupleWithMoreThan8Elements.Rest.Item1.Item5); Console.ReadKey(); Output :Rest: ((1, 4, 9, 16, 25, 36, 49, 64))Rest's 2nd element: 4Rest's 5th element: 25
System.Numerics Complex numbers
static void Main(string[] args){ var z1 = new Complex(); // this creates complex zero (0, 0) var z2 = new Complex(2, 4); var z3 = new Complex(3, 5); Console.WriteLine("Complex zero: " + z1); Console.WriteLine(z2 + " + " + z3 + " = " + (z2 + z3)); Console.WriteLine("|z2| = " + z2.Magnitude); Console.WriteLine("Phase of z2 = " + z2.Phase); Console.ReadLine();} Complex zero: (0, 0)
(2, 4) + (3, 5) = (5, 9) |z2| = 4,47213595499958 Phase of z2 = 1,10714871779409Output
System.Numerics Complex numbers cont.
static void Main(string[] args){ var z2 = new Complex(2, 4); var z3 = new Complex(3, 5); var z4 = Complex.Add(z2, z3); var z5 = Complex.Subtract(z2, z3); var z6 = Complex.Multiply(z2, z3); var z7 = Complex.Divide(z2, z3); Console.WriteLine("z2 + z3 = " + z4); Console.WriteLine("z2 - z3 = " + z5); Console.WriteLine("z2 * z3 = " + z6); Console.WriteLine("z2 / z3 = " + z7);
Console.ReadLine();}
Output
z2 + z3 = (5, 9) z2 - z3 = (-1, -1) z2 * z3 = (-14, 22)z2 / z3 = (0,76470588235, 0,058823529411)
Parallel Programming
Parallel ProgrammingFor Loop
using System.Threading.Tasks;..//serial implementation for (int i = 0; i < 10; i++) {//Do stuff .. anything}//parallel implementation Parallel.For(0, 10, i => { /*anything with i*/ } );
Parallel Programming PLINQ
bool[] results = new bool[arr.Length]; // arr is array of integersfor (int i = 0; i < arr.Length; i++) { results[i] = IsPrime(arr[i]); }//LINQ to Objects bool[] results1 = arr.Select(x => IsPrime(x)) .ToArray(); //PLINQbool[] results2 = arr.AsParallel().Select(x => IsPrime(x)) .ToArray();
Parallel Tasks(Debug Menu -> Windows -> Parallel Tasks):
thread-safe-data-structures
Queue : ConcurrentQueue<T>
ConcurrentQueue<int> queue = new ConcurrentQueue<int>();queue.Enqueue(10); int t;Console.WriteLine(queue.TryPeek(out t));Console.WriteLine(queue.TryDequeue(out t));
thread-safe-data-structures cont.Stack : ConcurrentStack<T>ConcurrentStack<int> stack = new ConcurrentStack<int>();stack.Push(10);stack.PushRange(new int[] { 1, 2, 3, 4, 5 }); int t;if (stack.TryPop(out t)){ Console.WriteLine("Pop: " + t);}if (stack.TryPeek(out t)){ Console.WriteLine("Peek: " + t);}int[] ts = new int[5];int count;if ((count = stack.TryPopRange(ts, 0, 3)) > 0){ Console.WriteLine("PopRange"); for (int i = 0; i < count; i++) { Console.WriteLine(ts[i]); }}
thread-safe-data-structures cont.
Collection : ConcurrentBag<T>ConcurrentBag<int> bag = new ConcurrentBag<int>(new int[] { 1, 1, 2, 3 });bag.Add(70); int t;bag.TryPeek(out t);Console.WriteLine(t); bag.Add(110); Console.WriteLine();for (int i = 0; i < 3; i++){ bag.TryTake(out t); Console.WriteLine(t);}
Another Additions• Code Contracts • (memory-mapped files) : you can use
managed code to access memory-mapped files in the same way that native Windows functions access memory-mapped files
Another Additions cont.
• Managed Extensibility Framework (MEF) is a component of .NET Framework 4.0 and Silverlight 4 for creating lightweight, extensible applications.
It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies
Thanks for Attending
Abed El-Azeem Bukhari (MCPD,MCTS,MCP)el-bukhari.com