Generalized cache with priority and time-to-live

C# Hard generics

Task «Generalized cache with priority and time-to-live»

Implement a generic class Cache<TKey, TValue> that stores items with a specified time-to-live (TimeToLive) and priority (int). When adding an item, if the cache exceeds the maximum size, the item with the lowest priority is removed, and if priorities are equal, the oldest item is removed. After the TimeToLive expires, the item is considered expired and is not returned when requested. Methods: Add(TKey key, TValue value, int priority) — adds or updates an item; TryGet(TKey key, out TValue value) — returns true if the key exists and is not expired, otherwise false; RemoveExpired() — removes all expired items. Implement thread safety using locks.

Input Format

First line: maximum cache size (int) and time-to-live in seconds (int). Second line: number of commands N (int). Then N lines, each command: 'add key value priority' or 'get key' or 'remove_expired'.

Output Format

For each 'get' command, output the value if the key is found and not expired, otherwise 'null'. For 'remove_expired', output the number of deleted items. For 'add', output nothing.

Examples

Example 1

INPUT
3 5 8 add a 10 1 add b 20 2 get a add c 30 3 add d 40 1 get b get d remove_expired
OUTPUT
10 null 40 1

Example 2

INPUT
2 10 6 add x 100 5 add y 200 5 get x add z 300 5 get y get z
OUTPUT
100 null 300
main.cs