/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; namespace QuantConnect.Util { /// /// Represents a read-only reference to any value, T /// /// The data type the reference points to public interface IReadOnlyRef { /// /// Gets the current value this reference points to /// T Value { get; } } /// /// Represents a reference to any value, T /// /// The data type the reference points to public sealed class Ref : IReadOnlyRef { private readonly Func _getter; private readonly Action _setter; /// /// Initializes a new instance of the class /// /// A function delegate to get the current value /// A function delegate to set the current value public Ref(Func getter, Action setter) { _getter = getter; _setter = setter; } /// /// Gets or sets the value of this reference /// public T Value { get { return _getter(); } set { _setter(value); } } /// /// Returns a read-only version of this instance /// /// A new instance with read-only semantics/gaurantees public IReadOnlyRef AsReadOnly() { return new Ref(_getter, value => { throw new InvalidOperationException("This instance is read-only."); }); } } /// /// Provides some helper methods that leverage C# type inference /// public static class Ref { /// /// Creates a new instance /// public static Ref Create(Func getter, Action setter) { return new Ref(getter, setter); } /// /// Creates a new instance /// public static IReadOnlyRef CreateReadOnly(Func getter) { return new Ref(getter, value => { throw new InvalidOperationException("This instance is read-only."); }); } /// /// Creates a new instance by closing over /// the specified variable. /// NOTE: This won't close over the variable input to the function, /// but rather a copy of the variable. This reference will use it's /// own storage. /// public static Ref Create(T initialValue) { return new Ref(() => initialValue, value => { initialValue = value; }); } } }