0Pricing
C# Academy · Lesson

unmanaged, notnull, new() (C# 6 emulation)

C# 6 supports class/struct/new() constraints; emulate newer notnull/unmanaged via guards, API shape, and conventions.

Constraints landscape

Goal: Use C# 6 generic constraints effectively.

  • class vs struct
  • new() for activator-less creation
  • Emulate notnull/unmanaged with guards and API design

class vs struct

class confines T to reference types; struct confines T to value types. Misuse fails at compile time.

using System;

// Works only for reference types
public static class RefBox
{
  public static string Show<T>(T value) where T : class
  {
    return value == null ? "null ref" : "ref: " + value.ToString();
  }
}

// Works only for value types
public static class ValBox
{
  public static string Show<T>(T value) where T : struct
  {
    return "value: " + value.ToString();
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    string s = "hello";
    int n = 42;

    Console.WriteLine(RefBox.Show<string>(s)); // OK
    Console.WriteLine(ValBox.Show<int>(n));    // OK

    // Console.WriteLine(RefBox.Show<int>(n)); // compile-time error (int is struct)
    // Console.WriteLine(ValBox.Show<string>(s)); // compile-time error (string is class)
  }
}

All lessons in this course

  1. unmanaged, notnull, new() (C# 6 emulation)
  2. Generic math (overview), generic attributes (when relevant)
  3. Reusable generic utilities
← Back to C# Academy