Skip to content

Instantly share code, notes, and snippets.

@neremin
Last active August 29, 2015 14:16
Show Gist options
  • Save neremin/db38857f74e344c3c849 to your computer and use it in GitHub Desktop.
Save neremin/db38857f74e344c3c849 to your computer and use it in GitHub Desktop.
public static class InterlockedFactory
{
public static T GetOrCreate<T>(ref T value, Func<T> valueFactory) where T : class
{
if (ReferenceEquals(value, null))
{
if (valueFactory == null)
{
throw new ArgumentNullException("valueFactory");
}
var newValue = valueFactory();
return Interlocked.CompareExchange(ref value, newValue, null) ?? newValue;
}
return value;
}
public static T GetOrCreate<T>(ref T value) where T : class, new()
{
if (ReferenceEquals(value, null))
{
var newValue = new T();
return Interlocked.CompareExchange(ref value, newValue, null) ?? newValue;
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment