Skip to content

Instantly share code, notes, and snippets.

@tabareh
Last active September 5, 2017 12:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tabareh/5bd796b9e3be40aeef325bbabab0e56d to your computer and use it in GitHub Desktop.
Save tabareh/5bd796b9e3be40aeef325bbabab0e56d to your computer and use it in GitHub Desktop.
C# Feature History

C# features history

C# 1.0

XML comments

				/// <summary>
				///  This class performs an important function.
				/// </summary>

Delegates ( a way to define a type for methods according to signature)

				// Declare a delegate:
				delegate void Del(int x);
				
				// Define a named method:
				void DoWork(int k) { /* ... */ }
				
				// Instantiate the delegate using the method as a parameter:
				Del d = new Del(DoWork);

Events using delegates as method types

				public event Del MyEvent
      {
          add
          {
              Console.WriteLine("Listener added!");
              _myEvent += value;
          }
          remove
          {
              Console.WriteLine("Listener removed!");
              _myEvent -= value;
          }
      }

Etc.

C# 2.0

Generics

				® public class Stack<T>

Partial types

				® partial class A

Anonymous methods

				// Create a delegate.
				delegate void Del(int x);
				
				// Instantiate the delegate using an anonymous method.
				Del d = delegate(int k) { /* ... */ };

Iterators

				® The most common way to create an iterator is to implement the GetEnumerator method on the IEnumerable interface
				® Then the type is usable in foreach statement

Nullable types

				® Nullable types are instances of the System.Nullable<T> struct. 
				® int? num = null;
				® The syntax T? is shorthand for Nullable<T>, where T is a value type.

Getter/setter separate accessibility

				public string Name
				{
				get { return m_name; }
				protected set { m_name = value; }
				}

Method group conversions (delegates)

				® simplifies the syntax that assigns a method to a delegate.
				® In delegate sample from C# 1.0, we can simplify
					◊ Del d = DoWork

Co- and Contra-variance for delegates

				® covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments. Covariance preserves assignment compatibility and contravariance reverses it.
					◊ Covariance
						public delegate Mammals HandlerMethod();
						// Covariance enables this assignment. Considering Dogs inherits from Mammals, and the following methods exist
						// public static Mammals MammalsHandler()
						// public static Dogs DogsHandler()
						HandlerMethod handlerDogs = DogsHandler;
					◊ Contravariance
						// Event hander that accepts a parameter of the EventArgs type.

//private void MultiHandler(object sender, System.EventArgs e) // although the event expects the KeyEventArgs parameter. this.button1.KeyDown += this.MultiHandler; // for an event that expects the MouseEventArgs parameter. this.button1.MouseClick += this.MultiHandler;

Static classes

				® A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated.

Delegate inference

C# 3.0

Implicitly typed local variables

				® var x= new int[50]; 

Object and collection initializers

				® Object examples
					◊ Cat cat = new Cat { Age = 10, Name = "Fluffy" };
					◊ var pet = new { Age = 10, Name = "Fluffy" };
					◊ new {p.ProductName, Price = p.UnitPrice};
				® Collection 
					◊ List<int> digits2 = new List<int> { 0 + 1, 12 % 3, MakeInt() };

Auto-Implemented properties

				® public double TotalPurchases { get; set; }

Anonymous types

				® var person = new { firstName = "John", lastName = "Smith" };

Extension methods

				® Public static MyCustomType ConvertToMyCustomType(this string obj);
				® "an string".ConvertToMyCustomType();

Query expressions

				from score in scores
				where score > 80
				select score;

Lambda expressions

				® A lambda expression is an anonymous function that you can use to create delegates or expression tree types.
				® More notes

Expression trees

				® Expression<Func<int, bool>> lambda = num => num < 5;
				® lambda.Compile()(8);

Partial methods

				®     Signatures in both parts of the partial type must match.
				®     The method must return void.
				®     No access modifiers are allowed. Partial methods are implicitly private.

C# 4.0

Dynamic binding

				using System.Dynamic;
				public class Table : DynamicObject
				    {
				        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
				        {
				                Console.WriteLine(binder.Name + "method was dynamically called");

Named and optional arguments

				® CalculateBMI(weight: 123, height: 64)
				® static int CalculateBMI(int weight, int height=128)

Tuples

				® A tuple is a data structure that has a specific number and sequence of elements
				® var tuple = Tuple.Create("cat", 2, true);

Generic co- and contravariance

				® Covariance: i.e. You can assign an instance of IEnumerable<Derived> to a variable of type IEnumerable<Base>.
				® Contravariance: i.e. You can assign an instance of IEnumerable<Base>  to a variable of type IEnumerable<Derived>.

Embedded interop types ("NoPIA")

C# 5.0

Asynchronous methods

				® Using Task class + async and await keywords for implementing/using the methods which will run in background
				® More info

Caller info attributes

				®  help in tracking information about the caller 
				public static void ShowCallerInfo([CallerMemberName] 
  string callerName = null, [CallerFilePath] string 
  callerFilePath = null, [CallerLineNumber] int callerLine=-1)
{

C# 6.0 (.net 4.5, VS 2015)

Compiler-as-a-service (Roslyn)

				® You can build code analysis tools with the same APIs that Microsoft is using to implement Visual Studio!

Import of static type members into namespace

				® using static System.Console;
				® WriteLine("Hello, World!");

Exception filters

				® catch (Exception e) when (Thread.CurrentPrincipal.Identity.Name == "JBOGARD") {

Await in catch/finally blocks

				® Allowed to use await in catch and finally block

Auto property initializers

				® public DateTime TimeStamp { get; set; } = DateTime.UtcNow;

Default values for getter-only properties

				® public DateTime TimeStamp { get; } = DateTime.UtcNow;

Expression-bodied members

				® public int Area => Length * Width;

Null propagator

				® return value?.Substring(

String Interpolation

				®  An interpolated string expression looks like a template string that contains expressions.
				® String s= $"{person.Name, 20} is {person.Age:D3} year {(p.Age == 1 ? "" : "s")} old."

nameof operator

				® WriteLine(nameof(person.Address.ZipCode)); // prints "ZipCode”

Dictionary initializer

				var myDict = new Dictionary<int, string>
				{
				    [1] = "Pankaj",
				    [2] = "Pankaj",
				    [3] = "Pankaj"
				};

C# 7.0 proposals[42]

Local functions

Pattern matching

Records / algebraic data types

Nullability tracking

Async streams and disposal

Strongly typed access to wire formats

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment