StefH/FluentBuilder

Unable to use `Func` and `Action` with the builder methods

dmoonfire opened this issue · 3 comments

I'm trying to use this library to create my objects, but I've encountered a problem. My library uses callbacks (System.Func and System.Action) pretty heavily, so I have classes like:

public class Operation
{
    public Func<int, string> ToStringCallback { get; set; }
    public Action<int> IntCallback { get; set; }
}

The resulting code is:

    public partial class OperationBuilder : Builder<Operation>
    {
        private bool _toStringCallbackIsSet;
        private Lazy<System.Func<int, string>> _toStringCallback = new Lazy<System.Func<int, string>>(() => new System.Func<int, string>(new object(), default(System.IntPtr)));
        public OperationBuilder WithToStringCallback(System.Func<int, string> value) => WithToStringCallback(() => value);
        public OperationBuilder WithToStringCallback(Func<System.Func<int, string>> func)
        {
            _toStringCallback = new Lazy<System.Func<int, string>>(func);
            _toStringCallbackIsSet = true;
            return this;
        }
        public OperationBuilder WithoutToStringCallback()
        {
            WithToStringCallback(() => new System.Func<int, string>(new object(), default(System.IntPtr)));
            _toStringCallbackIsSet = false;
            return this;
        }

        private bool _intCallbackIsSet;
        private Lazy<System.Action<int>> _intCallback = new Lazy<System.Action<int>>(() => new System.Action<int>(new object(), default(System.IntPtr)));
        public OperationBuilder WithIntCallback(System.Action<int> value) => WithIntCallback(() => value);
        public OperationBuilder WithIntCallback(Func<System.Action<int>> func)
        {
            _intCallback = new Lazy<System.Action<int>>(func);
            _intCallbackIsSet = true;
            return this;
        }
        public OperationBuilder WithoutIntCallback()
        {
            WithIntCallback(() => new System.Action<int>(new object(), default(System.IntPtr)));
            _intCallbackIsSet = false;
            return this;
        }

This produces errors when compling, mainly on these two lines:

WithToStringCallback(() => new System.Func<int, string>(new object(), default(System.IntPtr)));
WithIntCallback(() => new System.Action<int>(new object(), default(System.IntPtr)));

The constructors are the failure since those aren't allowed. A possibly alternative would be, but that might require some additional reflection/investigating. Sadly, it would add a lot more overhead to create an interface to handle these since the object being built is basically just a collection of callbacks.

new System.Action<int>((v1) => { });
new System.Func<int, string>((v1) => default(string));

Thank you.

@StefH, thank you. That looks exactly like what I needed.

StefH commented

Thanks for verifying.

I'll release a new version.