SlideShare una empresa de Scribd logo
1 de 26
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 Initialize public 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&quot; , bool param2  = false , int param3  = 24  ) { } As VB.NET, You can put default values for the parameters.  Optional Parameters
Named Parameters  Myfunction(“najah&quot;,50); // Error ! Myfunction(“najah&quot;,param3: 50); public void Myfunction( string param1 =“flykit&quot; , bool param2  = false , int param3  = 24  ) { }
COM interop ((Excel.Range)excel.Cells[1, 1]).Value = “Hiiiiiiiii&quot;; excel.Cells[1, 1].Value = &quot;Hiiiiiiiii&quot;;
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(&quot;Add&quot;, 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(&quot;Add&quot;, 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 = &quot;Hello&quot;;  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&quot;; 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&quot;; 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(&quot;1st item: {0}&quot;, squaresList.Item1); //1   Console.WriteLine(&quot;4th item: {0}&quot;, squaresList.Item4); //16   Console.WriteLine(&quot;8th item: {0}&quot;, squaresList.Rest); //(64) Console.ReadKey();     Console.WriteLine(Environment.NewLine);           
System.Tuple cont.   var tupleWithMoreThan8Elements =    System.Tuple.Create(&quot; is&quot;, 2.3, 4.0f,  new List<CHAR> { 'e', 't', 'h' }, “najah dotnet&quot;, new Stack<INT>(4), &quot;best&quot;, squaresList);    // we'll sort the list of chars in descending order    tupleWithMoreThan8Elements.Item4.Sort();    tupleWithMoreThan8Elements.Item4.Reverse();          Console.WriteLine(&quot;{0} {1} {2} {3}&quot;, tupleWithMoreThan8Elements.Item5,  tupleWithMoreThan8Elements.Item1,    string.Concat(tupleWithMoreThan8Elements.Item4),     tupleWithMoreThan8Elements.Item7); //  najah dotnet is the best Console.WriteLine(&quot;Rest: {0}&quot;, tupleWithMoreThan8Elements.Rest);  Console.WriteLine(&quot;Rest's 2nd element: {0}&quot;, tupleWithMoreThan8Elements.Rest.Item1.Item2);  Console.WriteLine(&quot;Rest's 5th element: {0}&quot;, tupleWithMoreThan8Elements.Rest.Item1.Item5);  Console.ReadKey();  Output : Rest: ((1, 4, 9, 16, 25, 36, 49, 64)) Rest's 2nd element: 4 Rest'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(&quot;Complex zero: &quot; + z1);      Console.WriteLine(z2 + &quot; + &quot; + z3 + &quot; = &quot; + (z2 + z3));        Console.WriteLine(&quot;|z2| = &quot; + z2.Magnitude);      Console.WriteLine(&quot;Phase of z2 = &quot; + z2.Phase);        Console.ReadLine(); } Complex zero: (0, 0)  (2, 4) + (3, 5) = (5, 9)  |z2| = 4,47213595499958  Phase of z2 = 1,10714871779409 Output
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(&quot;z2 + z3 = &quot; + z4);      Console.WriteLine(&quot;z2 - z3 = &quot; + z5);      Console.WriteLine(&quot;z2 * z3 = &quot; + z6);      Console.WriteLine(&quot;z2 / z3 = &quot; + 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 Programming For 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 integers for (int i = 0; i < arr.Length; i++) { results[i] = IsPrime(arr[i]);  } //LINQ to Objects bool[] results1 = arr.Select(x => IsPrime(x)) .ToArray();  //PLINQ bool[] 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(&quot;Pop: &quot; + t);} if (stack.TryPeek(out t)){ Console.WriteLine(&quot;Peek: &quot; + t);} int[] ts = new int[5]; int count; if ((count = stack.TryPopRange(ts, 0, 3)) > 0){ Console.WriteLine(&quot;PopRange&quot;);  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 ,[object Object],[object Object]
Another Additions cont. ,[object Object],[object Object]
Thanks for Attending Abed El-Azeem Bukhari  (MCPD,MCTS,MCP) el-bukhari.com

Más contenido relacionado

La actualidad más candente

DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
Travel management
Travel managementTravel management
Travel management
1Parimal2
 

La actualidad más candente (20)

Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
C++ Programming - 11th Study
C++ Programming - 11th StudyC++ Programming - 11th Study
C++ Programming - 11th Study
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
Pattern printing programs
Pattern printing programsPattern printing programs
Pattern printing programs
 
C++ Programming - 1st Study
C++ Programming - 1st StudyC++ Programming - 1st Study
C++ Programming - 1st Study
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
C#
C#C#
C#
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java scriptCodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
CodiLime Tech Talk - Grzegorz Rozdzialik: What the java script
 
Travel management
Travel managementTravel management
Travel management
 
C# console programms
C# console programmsC# console programms
C# console programms
 
Container adapters
Container adaptersContainer adapters
Container adapters
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
 

Similar a Whats new in_csharp4

Modify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdfModify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdf
mallik3000
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
ShriKant Vashishtha
 
COMP360 Assembler Write an assembler that reads the source code of an.pdf
COMP360 Assembler Write an assembler that reads the source code of an.pdfCOMP360 Assembler Write an assembler that reads the source code of an.pdf
COMP360 Assembler Write an assembler that reads the source code of an.pdf
fazalenterprises
 

Similar a Whats new in_csharp4 (20)

Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Modify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdfModify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdf
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
5 Rmi Print
5  Rmi Print5  Rmi Print
5 Rmi Print
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
.net progrmming part2
.net progrmming part2.net progrmming part2
.net progrmming part2
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
 
.net progrmming part1
.net progrmming part1.net progrmming part1
.net progrmming part1
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Thread
ThreadThread
Thread
 
COMP360 Assembler Write an assembler that reads the source code of an.pdf
COMP360 Assembler Write an assembler that reads the source code of an.pdfCOMP360 Assembler Write an assembler that reads the source code of an.pdf
COMP360 Assembler Write an assembler that reads the source code of an.pdf
 
How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 
39927902 c-labmanual
39927902 c-labmanual39927902 c-labmanual
39927902 c-labmanual
 

Más de Abed Bukhari

Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
Abed Bukhari
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
Abed Bukhari
 
Csharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsCsharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressions
Abed Bukhari
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
 
Csharp4 inheritance
Csharp4 inheritanceCsharp4 inheritance
Csharp4 inheritance
Abed Bukhari
 

Más de Abed Bukhari (8)

Csharp4 arrays and_tuples
Csharp4 arrays and_tuplesCsharp4 arrays and_tuples
Csharp4 arrays and_tuples
 
Csharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_eventsCsharp4 delegates lambda_and_events
Csharp4 delegates lambda_and_events
 
Csharp4 generics
Csharp4 genericsCsharp4 generics
Csharp4 generics
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
Csharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressionsCsharp4 strings and_regular_expressions
Csharp4 strings and_regular_expressions
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Csharp4 inheritance
Csharp4 inheritanceCsharp4 inheritance
Csharp4 inheritance
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Whats new in_csharp4

  • 1. What’s New in C# 4.0 Abed El-Azeem Bukhari (MCPD,MCTS,MCP) el-bukhari.com
  • 2. 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?
  • 3. Object and collection Initialize public 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?
  • 4. What’s new in C# 4.0 public void Myfunction( string param1 =“flykit&quot; , bool param2 = false , int param3 = 24 ) { } As VB.NET, You can put default values for the parameters. Optional Parameters
  • 5. Named Parameters Myfunction(“najah&quot;,50); // Error ! Myfunction(“najah&quot;,param3: 50); public void Myfunction( string param1 =“flykit&quot; , bool param2 = false , int param3 = 24 ) { }
  • 6. COM interop ((Excel.Range)excel.Cells[1, 1]).Value = “Hiiiiiiiii&quot;; excel.Cells[1, 1].Value = &quot;Hiiiiiiiii&quot;;
  • 7. Variance IList<string> strings = new List<string>(); IList<object> objects = strings;// Error IEnumerable<object> objects = strings;
  • 8. Dynamic Programming object calculator = GetCalculator(); Type calculatorType = calculator.GetType(); object res = calculatorType.InvokeMember(&quot;Add&quot;, 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(&quot;Add&quot;, 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);
  • 9. Dynamic Programming cont. dynamic x = 1; dynamic y = &quot;Hello&quot;; 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)
  • 10. Diffrence between var and dynamic keyword: string s = “We are DotNet Students&quot;; 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&quot;; dynamic test = s; Console.WriteLine (test.MethodDoesnotExist());// OK! Used for programming with COM or JavaScript which can have runtime properties!!
  • 11. System.Tuple var squaresList = System.Tuple.Create(1, 4, 9, 16, 25, 36, 49, 64);      Console.WriteLine(&quot;1st item: {0}&quot;, squaresList.Item1); //1   Console.WriteLine(&quot;4th item: {0}&quot;, squaresList.Item4); //16   Console.WriteLine(&quot;8th item: {0}&quot;, squaresList.Rest); //(64) Console.ReadKey();    Console.WriteLine(Environment.NewLine);          
  • 12. System.Tuple cont.   var tupleWithMoreThan8Elements =   System.Tuple.Create(&quot; is&quot;, 2.3, 4.0f, new List<CHAR> { 'e', 't', 'h' }, “najah dotnet&quot;, new Stack<INT>(4), &quot;best&quot;, squaresList);   // we'll sort the list of chars in descending order   tupleWithMoreThan8Elements.Item4.Sort();   tupleWithMoreThan8Elements.Item4.Reverse();         Console.WriteLine(&quot;{0} {1} {2} {3}&quot;, tupleWithMoreThan8Elements.Item5, tupleWithMoreThan8Elements.Item1,   string.Concat(tupleWithMoreThan8Elements.Item4),    tupleWithMoreThan8Elements.Item7); // najah dotnet is the best Console.WriteLine(&quot;Rest: {0}&quot;, tupleWithMoreThan8Elements.Rest); Console.WriteLine(&quot;Rest's 2nd element: {0}&quot;, tupleWithMoreThan8Elements.Rest.Item1.Item2); Console.WriteLine(&quot;Rest's 5th element: {0}&quot;, tupleWithMoreThan8Elements.Rest.Item1.Item5); Console.ReadKey(); Output : Rest: ((1, 4, 9, 16, 25, 36, 49, 64)) Rest's 2nd element: 4 Rest's 5th element: 25     
  • 13. 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(&quot;Complex zero: &quot; + z1);     Console.WriteLine(z2 + &quot; + &quot; + z3 + &quot; = &quot; + (z2 + z3));       Console.WriteLine(&quot;|z2| = &quot; + z2.Magnitude);     Console.WriteLine(&quot;Phase of z2 = &quot; + z2.Phase);       Console.ReadLine(); } Complex zero: (0, 0) (2, 4) + (3, 5) = (5, 9) |z2| = 4,47213595499958 Phase of z2 = 1,10714871779409 Output
  • 14. 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(&quot;z2 + z3 = &quot; + z4);     Console.WriteLine(&quot;z2 - z3 = &quot; + z5);     Console.WriteLine(&quot;z2 * z3 = &quot; + z6);     Console.WriteLine(&quot;z2 / z3 = &quot; + z7);     Console.ReadLine(); } Output z2 + z3 = (5, 9) z2 - z3 = (-1, -1) z2 * z3 = (-14, 22) z2 / z3 = (0,76470588235, 0,058823529411)
  • 16.  
  • 17.  
  • 18. Parallel Programming For 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*/ } );
  • 19. Parallel Programming PLINQ bool[] results = new bool[arr.Length]; // arr is array of integers for (int i = 0; i < arr.Length; i++) { results[i] = IsPrime(arr[i]); } //LINQ to Objects bool[] results1 = arr.Select(x => IsPrime(x)) .ToArray(); //PLINQ bool[] results2 = arr.AsParallel().Select(x => IsPrime(x)) .ToArray();
  • 20. Parallel Tasks (Debug Menu -> Windows -> Parallel Tasks):
  • 21. 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));
  • 22. 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(&quot;Pop: &quot; + t);} if (stack.TryPeek(out t)){ Console.WriteLine(&quot;Peek: &quot; + t);} int[] ts = new int[5]; int count; if ((count = stack.TryPopRange(ts, 0, 3)) > 0){ Console.WriteLine(&quot;PopRange&quot;); for (int i = 0; i < count; i++) { Console.WriteLine(ts[i]); }}
  • 23. 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);}
  • 24.
  • 25.
  • 26. Thanks for Attending Abed El-Azeem Bukhari (MCPD,MCTS,MCP) el-bukhari.com