Search code examples
c#.netfactoryfactory-pattern

How do I use a factory generated object?


I am a student trying to learn factory methods in C# and I would love some help. I now have a CommanderFactory that creates a "Commander()". Let's say I generate a "Commander()" with both values set to 1. (val1 = 1, val2 = 2). How Would I now go about doing calculations on these values? As seen in the calculator class above. I have a parameter for "Commander", but how do I "select" the values inside, and do addition on them?

namespace FactoryCalculator
{
    public static class Calculator
    {
        public static int Add(Commander)
        {
            return val1 + val2;
        }

    }

    public class Commander
    {
        private Commander()
        {
        }

        public int Val1 { get; set; }
        public int Val2 { get; set; }

        public static class CommanderFactory
        {
            public static Commander CreateNewCommander(int val1, int val2)
            {
                return new Commander()
                {
                    Val1 = val1,
                    Val2 = val2
                };
            }

        }
    }
}

Solution

  • This is the syntax for accessing a Property ([instance].[property]):

    public static int Add(Commander c)
    {
        return c.Val1 + c.Val2;
    }