Created
October 25, 2025 11:40
-
-
Save sunmeat/1e9aad76764a1b1329111b5e7d648007 to your computer and use it in GitHub Desktop.
generic class example C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| namespace GenericClassExample | |
| { | |
| class Point<T> | |
| { | |
| T x; // поле типу T | |
| T y; | |
| public T X // властивість типу T | |
| { | |
| get { return x; } | |
| set { x = value; } | |
| } | |
| public T Y | |
| { | |
| get { return y; } | |
| set { y = value; } | |
| } | |
| public Point(T x, T y) // аргументи типу T | |
| { | |
| this.x = x; | |
| this.y = y; | |
| } | |
| public Point() | |
| { | |
| x = default(T); | |
| y = default(T); | |
| // default(Int32) - 0 | |
| // default(Boolean) - false | |
| // default(String) - "" | |
| } | |
| } | |
| class Program | |
| { | |
| static void Main() | |
| { | |
| var a = new Point<int>(10, 20); | |
| Console.WriteLine("x = {0}, y = {1}", a.X, a.Y); | |
| var c = new Point<double>(10.5, 20.5); | |
| Console.WriteLine("x = {0}, y = {1}", c.X, c.Y); | |
| var d = new Point<string>("десять", "двадцять"); // where T : struct | |
| Console.WriteLine("x = {0}, y = {1}\n", d.X, d.Y); | |
| // http://stackoverflow.com/questions/6584263/whats-the-meaning-of-apostrophe-number-in-the-object-type-of-properties-wit | |
| Console.WriteLine(typeof(Point<int>)); | |
| Console.WriteLine(typeof(Point<double>)); | |
| Console.WriteLine(typeof(Point<string>)); | |
| Console.WriteLine(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment