Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created October 25, 2025 11:46
Show Gist options
  • Save sunmeat/accd0bd3c3f94f093db49856ea3cadf8 to your computer and use it in GitHub Desktop.
Save sunmeat/accd0bd3c3f94f093db49856ea3cadf8 to your computer and use it in GitHub Desktop.
constraints C#
using System.Text;
namespace GenericClassExample2
{
// https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
class Box<T> where T : class, new()
{
protected T innerObject;
public Box()
{
innerObject = new T();
}
public Box(T someObject)
{
innerObject = someObject;
}
public T InnerObject
{
get
{
return innerObject;
}
set
{
innerObject = value;
}
}
public void Print()
{
Console.Write(innerObject);
if (typeof(T).Name.Contains("Box")) Console.Write(",");
Console.WriteLine(" знаходиться в коробці.");
}
public override string ToString()
{
return "коробка, всередині якої лежить " + innerObject;
}
}
class Cat
{
public override string ToString()
{
return "кішка";
}
}
class Program
{
static void Main()
{
Console.OutputEncoding = Encoding.UTF8;
// var a = new Box<int>(); // тип 'int' має бути типом посилання, щоб використовувати його як параметр 'T' у загальному типі або методі
var b = new Box<Cat>();
b.Print();
Console.WriteLine(b + ".\n");
Thread.Sleep(2000);
var c = new Box<Box<Cat>>();
c.Print();
Console.WriteLine(c + ".\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment