Skip to content

Instantly share code, notes, and snippets.

@chucker
Created June 8, 2019 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chucker/dcdcf758a46fe06f8786821529b1a929 to your computer and use it in GitHub Desktop.
Save chucker/dcdcf758a46fe06f8786821529b1a929 to your computer and use it in GitHub Desktop.
using System;
[System.Runtime.CompilerServices.PropertyWrapper]
public class Expirable<TValue> : Attribute
{
private TimeSpan duration;
private DateTime expirationDate;
private TValue? innerValue = null;
public TValue? Value
{
get => return HasExpired ? null : innerValue;
set
{
expirationDate = DateTime.Now + duration;
innerValue = value;
}
}
public Expirable(TimeSpan duration)
{
this.duration = duration;
}
private bool HasExpired => expirationDate < DateTime.Now;
}
public struct Tokens
{
[Expirable(duration: TimeSpan.FromSeconds(3))]
static string AuthenticationToken { get; set; }
}
Tokens.AuthenticationToken = "asdijoaisjdoiajsd";
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine(Tokens.AuthenticationToken); // prints the token
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine(Tokens.AuthenticationToken); // prints null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment