using System;
namespace Umbraco.Cms.Core
{
///
/// Represents a value that can be assigned a value.
///
/// The type of the value
public class Settable
{
private T? _value;
///
/// Assigns a value to this instance.
///
/// The value.
public void Set(T? value)
{
if (value is not null)
{
HasValue = true;
}
_value = value;
}
///
/// Assigns a value to this instance by copying the value
/// of another instance, if the other instance has a value.
///
/// The other instance.
public void Set(Settable other)
{
// set only if has value else don't change anything
if (other.HasValue) Set(other.Value);
}
///
/// Clears the value.
///
public void Clear()
{
HasValue = false;
_value = default (T);
}
///
/// Gets a value indicating whether a value has been assigned to this instance.
///
public bool HasValue { get; private set; }
///
/// Gets the value assigned to this instance.
///
/// An exception is thrown if the HasValue property is false.
/// No value has been assigned to this instance.
public T? Value
{
get
{
if (HasValue == false)
throw new InvalidOperationException("The HasValue property is false.");
return _value;
}
}
///
/// Gets the value assigned to this instance, if a value has been assigned,
/// otherwise the default value of .
///
/// The value assigned to this instance, if a value has been assigned,
/// else the default value of .
public T? ValueOrDefault()
{
return HasValue ? _value : default(T);
}
///
/// Gets the value assigned to this instance, if a value has been assigned,
/// otherwise a specified default value.
///
/// The default value.
/// The value assigned to this instance, if a value has been assigned,
/// else .
public T? ValueOrDefault(T defaultValue)
{
return HasValue ? _value : defaultValue;
}
///
public override string? ToString()
{
return HasValue ? _value?.ToString() : "void";
}
}
}