Skip to content

FR CSharp Keyword notnull

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: notnull

Manuel C# · Guide pratique

Restriction générique pour un type qui doit être non nullable. Les violations sont évaluées par une analyse nullable, et non par une exclusion automatique de l'exécution.

Exemple simple (Example.cs)

Enregistrez cet exemple séparément dans Example.cs. Exécutez-le indépendamment des autres exemples de cette page.

Example.cs:

// PROJECT-EXAMPLE
T Echo<T>(T value) where T : notnull => value;
System.Console.WriteLine(Echo("ore"));

Résultat:

ore

Syntaxe

where T : notnull

Exemple 1 : formulaire de base

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Values.Identity("ore"));
    }
}
public static class Values { public static T Identity<T>(T value) where T : notnull => value; }

Exemple 2 : une autre forme pratique

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Storage<int> storage = new();
        storage.Put(1, "ore");
        Console.WriteLine(storage.Get(1));
    }
}
public class Storage<TKey> where TKey : notnull { private readonly Dictionary<TKey, string> values = new(); public void Put(TKey key, string value) { values[key] = value; } public string Get(TKey key) => values[key]; }

Source officielle : Microsoft Apprendre.

Clone this wiki locally