container icon indicating copy to clipboard operation
container copied to clipboard

Invalid Parameter default in derived Method

Open ENikS opened this issue 6 years ago • 0 comments

Invalid default value in overridden method parameters

Starting with Unity v5, parameters with default values are initialized with that value in case import can not be resolved.

Values in derived types

Consider the following example:

        public class TestType
        {
            [InjectionMethod]
            public virtual void Method(int value = 11) => Value = value;


            public virtual int Expected => 11;
            public virtual object Value { get; protected set; }
        }

        public class TestTypeDerived : TestType
        {
            public override void Method(int value = 22) => Value = value;

            public override int Expected => 22;
        }

        [TestMethod]
        public void TestCase()
        {
            var original = Container.Resolve<TestType>();
            var derived = Container.Resolve<TestTypeDerived>();

            // Validate
            Assert.IsNotNull(original);
            Assert.AreEqual(original.Expected, original.Value);

            Assert.IsNotNull(derived);
            Assert.AreEqual(derived.Expected, derived.Value);  <-- fails 
        }

TestType defines virtual method marked for injection. By default int is not registered, so Unity uses default value to invoke the method. In derived type TestTypeDerived the method is overridden with different default value, but when resolved, default value from parent type is used.

ENikS avatar Nov 19 '20 22:11 ENikS