Skip to content

CSharp Keyword where generic type constraint

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: where — обмеження параметра типу

Довідник C# · Практичне керівництво

Задає вимоги до параметра типу: базовий клас, інтерфейс, class/struct, new(), notnull, unmanaged та інші дозволені комбінації.

Простий приклад (Example.cs)

Збережіть цей приклад окремо як Example.cs. Запускайте його незалежно від інших прикладів на сторінці.

Example.cs:

// PROJECT-EXAMPLE
T Create<T>() where T : new() => new T();
System.Console.WriteLine(Create<Item>().Name);
class Item { public string Name => "Ore"; }

Результат:

Ore

Синтаксис

where T : constraint1, constraint2

Приклад 1: базова форма

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)
    {
        Counter counter = Factory.Create<Counter>();
        Console.WriteLine(counter.Value);
    }
}
public class Counter { public int Value => 7; }
public static class Factory { public static T Create<T>() where T : class, new() => new T(); }

Приклад 2: інша практична форма

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.Sum<Number>());
    }
}
public interface IValue { int Value { get; } }
public readonly struct Number : IValue { public int Value => 5; }
public static class Values { public static int Sum<T>() where T : struct, IValue { T value = new(); return value.Value; } }

Офіційне джерело: Microsoft Learn.

Clone this wiki locally