9 January, 2022

Programming in C#

Generic

Using generics with type constraints:

void Run<T>() where T: class {
}

public class TeachRepository<T> : ITeachRepository<T> where T : class, IEntity, new()

T can be restrictd by class, struct. Multiple restrictions are separated by , (comma).

Reflection

var t = existing.GetType();
var p = existing.GetType().GetProperty("DisplayName");
p?.SetValue(existing, client.DisplayName);

Measure execution Time

using System.Diagnostics;

var watch = new Stopwatch();

watch.Start();

// do something meaningfull

watch.Stop();

var duration = watch.ElapsedMilliseconds;

ASP.NET

[HttpPost]
public HttpResponseMessage GetList(int id, JObject parameter)
{
  // ...
}