Skip to content

History

Kota edited this page Feb 19, 2019 · 8 revisions

C#

1.0 (2002)

  • Hello, World!

2.0 (2005)

  • Generic

3.0 (2007)

  • cs => cs.Linq

4.0 (2010)

  • dynamic

5.0 (2012)

  • async

6.0 (2005)

Language Features

  • Auto Property Initializer
public Guid Id { get; } = Guid.NewGuid();
  • Primary Constructor
public class Money(string currency, decimal amount)
{
  public string Currency { get; } = currency;
  public string Amount { get; } = amount;
}
  • using Static Typename
using System.Console;
class Program
{
  public static void Main()
  {
    WriteLine("Hello World!");
  }
}
  • Dictionary Initializers
var _users = new Dictionary<string, string>() { 
  ["admin"] = "Ram",
  ["guest"] = "Sham"
}
// earlier
var _users = new Dictionary<string, string>() { 
  { "admin", "Ram" },
  { "guest", "Sham" }
}

  • Event Initializer : Wiring up an event while creating the object
  • Numeric Literals
public byte Code { get; } = 0b1100;
public long Length { get; } = 1_000_000_000;
  • Declaration Expression
foreach (var n in var odd = numbers(n +. n %2 == 1).ToList())
{
}

// old
var amount = 0;
decimal.TryParse("10.0", out amount);

// new
decimal.TryParse("10.0", var out amount);
  • Conditional Access
var name = action?.Method?.Name ?? "no name";
  • Await in Catch block

Compiler Features

  • Rosyln : .Net Compiler -> Open Source
  • Manual Compilation
    • Nuget package Microsoft.CodeAnalysis.CSharp
\\ A code.cs file has class "Greeter" and method "SayHello"

var code = File.readAllText("code.cs");
var tree = SyntaxFactory.ParseSyntaxTree(code);
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var reference = new MetadataFileReference(typeof(object).Assembly.Location)

var compilation = CSharpCompilation.Create("test").WithOptions(options).AddSyntaxTrees(tree).AddReferences(reference);

var diagnostics = compilation.GetDiagnostics();
foreach (var diagnostic in diagnostics ) 
{
  System.Console.WriteLine(diagnostic.ToString());
}

using stream(var stream = new MemoryStream())
{
  compilation.Emit(stream);

  var assembly = Assembly.Load(stream.GetBuffer());
  var type = assembly.GetType("Greeter");
  var greeter = Activator.CreateInstance(type);
  var method = type.GetMethod("SayHello");
  method.Invoke(greeter, null);
}

Clone this wiki locally