Advertisement
Guest User

TestCsharpVersion

a guest
Mar 6th, 2014
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.85 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace TestCsharpVersion
  7. {
  8.     class Program
  9.     {
  10.         //This should give an error since CSharp 3 does not support optional params
  11.         private void TestOptionalParam(string myOptional = "foobar")
  12.         {
  13.         }
  14.  
  15.         static void Main(string[] args)
  16.         {
  17.             //Example from http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/
  18.             //For C# version 5 this should return 100, 110, 120 and for C# version 4 or lower this should return 120, 120, 120
  19.             var values = new List<int>() { 100, 110, 120 };
  20.             var funcs = new List<Func<int>>();
  21.             foreach (var v in values)
  22.                 funcs.Add(() => v);
  23.             foreach (var f in funcs)
  24.                 Console.WriteLine(f());
  25.  
  26.  
  27.             //Logic to check if we're on C# 5
  28.             var testList = new List<string> { "a", "b" };
  29.             var lambdas = new List<Func<string>>();
  30.             var result = "";
  31.  
  32.             //Capture using foreach
  33.             foreach (var test in testList)
  34.             {
  35.                 lambdas.Add(() => test);
  36.             }
  37.  
  38.             //Read the captured vars
  39.             foreach (var lamdba in lambdas)
  40.             {
  41.                 result += lamdba();
  42.             }
  43.  
  44.             //Check if it's C# 5 behavior
  45.             if (result == "ab")
  46.             {
  47.                 result = "This is C# 5 or higher";
  48.             }
  49.             else if (result == "bb")
  50.             {
  51.                 result = "This is C# 4 or lower";
  52.             }
  53.             else
  54.             {
  55.                 result = "Unexpected result, no idea which C# version";
  56.             }
  57.  
  58.             Console.WriteLine(result);
  59.             Console.ReadLine();
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement