Skip to content

Instantly share code, notes, and snippets.

@SteveDunn
Last active March 5, 2022 07:12
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 SteveDunn/a03953236e08c4818cd992dc0101aa23 to your computer and use it in GitHub Desktop.
Save SteveDunn/a03953236e08c4818cd992dc0101aa23 to your computer and use it in GitHub Desktop.
In response to an .NET Runtime API request (https://github.com/dotnet/runtime/issues/62112), The proposal was for a way to use _either_ the default values in a list, **or** the values bound from configuration. This simple gist shows an alternative, that is simply a custom `ICollection`
using System.Collections;
using Microsoft.Extensions.Configuration;
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false);
var options = new MyImageProcessingOptions();
var config = builder.Build();
config.Bind("MyImageProcessingOptions", options);
Console.WriteLine(string.Join(",", options.ResizeWidths));
public class MyImageProcessingOptions
{
public DefaultableCollection<int> ResizeWidths { get; } = new(100, 200, 400, 800);
}
public class DefaultableCollection<T> : ICollection<T>
{
private readonly List<T> _items;
private bool _overridden;
public DefaultableCollection(params T[] defaults) => _items = defaults.ToList();
public void Add(T value)
{
if (!_overridden)
{
_overridden = true;
_items.Clear();
}
_items.Add(value);
}
public void Clear() => _items.Clear();
public bool Contains(T item) => _items.Contains(item);
public void CopyTo(T[] array, int arrayIndex) => _items.CopyTo(array, arrayIndex);
public bool Remove(T item) => _items.Remove(item);
public int Count => _items.Count;
public bool IsReadOnly => false;
public IEnumerator<T> GetEnumerator() => _items.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
{
"MyImageProcessingOptions": {
"ResizeWidths": [
"42",
"69",
"666"
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment