Created
October 6, 2025 11:55
-
-
Save sunmeat/20bf753da3a7f97abb559b2412d555e1 to your computer and use it in GitHub Desktop.
properties 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
using System.Text; | |
namespace PropertiesExample | |
{ | |
/* | |
у .net властивості (properties) — це компоненти класу, які надають гнучкий механізм | |
для читання, запису або обчислення значень полів. | |
вони часто використовуються як заміна публічних полів для контролю доступу | |
та модифікації даних. | |
властивості дозволяють інкапсулювати дані та приховувати внутрішні деталі реалізації, | |
при цьому надаючи доступ до цих даних через методи доступу (get і set). | |
це забезпечує зручний синтаксис та додатковий рівень абстракції. | |
*/ | |
public class Person | |
{ | |
// автоматична властивість для імені (get/set) | |
public string Name { get; set; } = "Олександр"; | |
// властивість з користувацькою реалізацією для віку (з валідацією) | |
private uint age = 18; | |
public uint Age | |
{ | |
get | |
{ | |
return age; | |
} | |
set | |
{ | |
if (value >= 0 && value <= 100) | |
age = value; | |
// інакше залишається поточне значення | |
} | |
} | |
// властивість тільки для читання для повного імені (обчислювана) | |
public string FullName | |
{ | |
get | |
{ | |
return $"{Name} Ковальчук"; // приклад обчислення | |
} | |
} | |
// властивість тільки для ініціалізації (init-only, C# 9+) | |
public string Email { get; init; } = "[email protected]"; | |
// required властивість (С# 11+) | |
// новинка для обов'язкових полів при створенні об'єкта | |
// значення можна встановити тільки під час ініціалізації | |
public required string Address { get; set; } | |
// властивість-лямбда (expression-bodied, C# 6+ для зручності) | |
public bool IsAdult => Age >= 18; | |
// властивість для позиції (складена, з вкладеною структурою) | |
public Point Position { get; set; } = new Point(); | |
// вкладена структура для демонстрації | |
public struct Point | |
{ | |
public Point() | |
{ | |
X = 10; | |
Y = 20; | |
} | |
public int X { get; set; } | |
public int Y { get; set; } | |
} | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
Console.OutputEncoding = Encoding.UTF8; | |
// створення об'єкта з init-only та required (C# 11+) | |
var person = new Person | |
{ | |
Email = "[email protected]", // init-only можна встановити тільки тут | |
Address = "вул. Шевченка, 1" // required | |
}; | |
Console.WriteLine("початкове ім'я: {0}", person.Name); | |
Console.WriteLine("початковий вік: {0}", person.Age); | |
// тестування set для авто-властивості | |
person.Name = "Микола"; | |
Console.WriteLine("оновлене ім'я: {0}", person.Name); | |
// тестування властивості з валідацією | |
person.Age = 25; | |
Console.WriteLine("вік після 25: {0}", person.Age); | |
person.Age = 234; // не зміниться | |
Console.WriteLine("вік після 234 (без змін): {0}", person.Age); | |
// read-only властивість | |
Console.WriteLine("повне ім'я: {0}", person.FullName); | |
// властивість-лямбда | |
Console.WriteLine("дорослий: {0}", person.IsAdult); | |
Console.WriteLine("позиція: X={0}, Y={1}", person.Position.X, person.Position.Y); | |
// спроба змінити init-only після створення (помилка компіляції, але для демо - коментар) | |
// person.Email = "[email protected]"; // помилка: init-only | |
Console.WriteLine("\nдемонстрація властивостей завершено."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment