C# Advanced Introduction
C# Advanced covers the parts of C# that inspect running programs, shape asynchronous work, and handle memory directly. It builds on the beginner and intermediate bands without teaching them again.
A description typed by hand
The program prints three lines that the author typed as literals. The Sensor class sits in the same file.
using System;
class Sensor
{
public string Name;
public int Level;
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Sensor");
Console.WriteLine("Name");
Console.WriteLine("Level");
}
}Reading the type itself
This snippet is a preview of reflection. It reads the class name and the field names from the type itself.
using System;
using System.Collections.Generic;
using System.Reflection;
class Sensor
{
public string Name;
public int Level;
}
class Program
{
static void Main(string[] args)
{
Type type = typeof(Sensor);
Console.WriteLine(type.Name);
FieldInfo[] fields = type.GetFields();
List<string> names = new List<string>();
foreach (FieldInfo field in fields)
{
names.Add(field.Name);
}
names.Sort();
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
string[] areas = { "Reflection", "Async", "Patterns" };
int count = 1;
foreach (string area in areas)
{
Console.WriteLine(count + ". " + area);
count = count + 1;
}
}
}Key points
- Reflection and attributes read type information at run time and mark types with data.
- Async at depth covers cancellation, configured awaits, streams, and lightweight tasks.
- Span and Memory lessons cover slices of memory without copying the data.
- Patterns at depth cover relational, list, and nested matches.
- Generics at depth cover static abstract members, operators, and conversions.
- Nullable at depth covers defaulting values and guarded null checks.
- Pointers lessons cover ref locals, unsafe code, and fixed buffers.
- Source generators lessons cover code added to a program at build time.
In this example, the array holds three area names. The foreach loop prints each name with a counter. The counter rises by one after each line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In the preview snippet, where do the field names come from?