Multi items Return from a Method

Tonight I was watching a TV show on YouTube. Suddenly one thing just come up my mind. I can accept multiple items as input parameter in a method, how can I get multiple items back from a Method as return.
So after a little bit thinking I found few ways, for example define a type with return items or define a anonymous type with return items and then return this anonymous type from that Method.

The code I wrote for this is as below,

namespace MultiItemsReturn
{
    using System;
    using System.Runtime.InteropServices;
    class Program
    {
        static void Main(string[] args)
        {
            ReturnTester returnTester = new ReturnTester();
            var areaUsingDynamic = returnTester.AreaModifierUsingDynamic(10, 12);
            var areaUsingType = returnTester.AreaModifierUsingType(10, 12);
            Console.WriteLine("{0} - {1}, {2}, {3}", areaUsingDynamic.description, areaUsingDynamic.height, areaUsingDynamic.width, areaUsingDynamic.area);
            Console.WriteLine("{0} - {1}, {2}, {3}", areaUsingType.Description, areaUsingType.Height, areaUsingType.Width, areaUsingType.TotalArea);
        }
    }
 
    public class ReturnTester
    {
        public const string ReturnTesterDescription = "Mutltiple items returns";
        private const int proportion = 100;
 
        public ReturnTester() { }
 
        public dynamic AreaModifierUsingDynamic(int width, int height, string description = ReturnTester.ReturnTesterDescription)
        {
            return new
            {
                width = width * proportion,
                height = height * proportion,
                area = width * height,
                description = description
            };
        }
 
        public Area AreaModifierUsingType(int width, int height, string description = ReturnTester.ReturnTesterDescription)
        {
            return new Area
            {
                Width = width * proportion,
                Height = height * proportion,
                TotalArea = width * height,
                Description = description
            };
        }
    }
 
    public class Area
    {
        public int Width { getset; }
        public int Height { getset; }
        public int TotalArea { getset; }
        public string Description { getset; }
    }
}

The output of the code is as below,


Mutltiple items returns - 1200, 1000, 120
Mutltiple items returns - 1200, 1000, 120
Press any key to continue . . . .


happy to learn from others.

Thanks
mohammad

No comments:

Post a Comment