Crap I always forget...

A simple parallel task operation might look like this:

using System.Threading.Tasks;
void MainThreadMethod ()
{
    Task.Factory.StartNew (() => wc.DownloadString ("http://...")).ContinueWith (
        t => label.Text = t.Result, TaskScheduler.FromCurrentSynchronizationContext()
    );
}

The key is TaskScheduler.FromCurrentSynchronizationContext() which will reuse the SynchronizationContext.Current of the thread calling the method (here the main thread that is running MainThreadMethod) as a way to marshal back calls to that thread. This means if the method is called on the UI thread, it will run the ContinueWith operation back on the UI thread.
If the code is starting tasks from other threads, use the following pattern to create a reference to the UI thread and the task can still call back to it:

static Context uiContext = TaskScheduler.FromCurrentSynchronizationContext();

If you need to invoke on the UI thread, look here

To camel case

Char.ToLowerInvariant(name[0]) + name.Substring(1)

Run an asynchronous task inside a synchronous one:

_clientSecret  = Task.Run(async () => await secretService.GetSecretUsingName(B2CSecretName).ConfigureAwait(false)).GetAwaiter().GetResult();

Without Yield

public static IEnumerable<int> GreaterThan(int[] arr, int gt) 
{     
    List<int> temp = new List<int>();
    foreach (int n in arr) {
        if (n > gt) temp.Add(n); 
        }
    return temp; 
}

With Yield (from Telerik)

public static IEnumerable<int> GreaterThan(int[] arr, int gt) 
{
    foreach (int n in arr) {
        if (n > gt) yield return n;     
        } 
    }

Throw exception in expressions

class Student
{
    private string studentName;
    // Expression – Bodied Constructor -- Throw Exception
    public Student(string name) => studentName = name ?? throw new ArgumentNullException();
}

or

// Expression - Properties - Throw Exception
public string Name
{
    get => studentName;
    set => studentName = value ?? throw new ArgumentNullException();
}

Turning a collection of objects into a List of objects

List<object> entityList = (objCollection as IEnumerable<object>).Cast<object>().ToList();

Getting an attribute from a class when you only have an instance (Core & 4.61)

The example attribute here is 'MergeableContentAttribute'

HtmlClass = entity.GetType().GetTypeInfo().GetCustomAttribute<MergeableContentAttribute>().HtmlClass

Reinstantiating an object from it's name and JSON string

var qualifiedName = Type.GetType(message.NotificationObject.Name);
var objectForNotification =  (ObjectForNotification)JsonConvert.DeserializeObject(message.NotificationObject.SerializedObject, qualifiedName);
Crap I always forget...
Share this