Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return different object types in case statement?

How can I return different object types in my case statement?

    public object?? CreateObjectType(JToken token)
    {
        switch (token["type"].Value<string>())
        {
            case "Car":
                var Car = new Car();
                return car;

            case "Boat":
                var boat = new Boat();
                return boat;
            ..... 
        }
    }

Do I need to create an abstract/interface class to accomplish this? An example of this would be great.

like image 575
Freddy. Avatar asked Jan 26 '23 09:01

Freddy.


2 Answers

The easiest way to tackle this would be to use an interface (in my mind):

using System;

namespace Test
{
    public class Test
    {
        public IVehicle CreateObjectType(JToken token)
        {
            switch(token["type"].Value<string>())
            {
                case "Car":
                    return new Car();

                case "Boat":
                    return new Boat();

                default:
                    throw new NotImplementedException();
            }
        }
    }

    public class Boat : IVehicle { }

    public class Car : IVehicle { }

    public interface IVehicle { }
}

Alternatively, you could do some form of inheritance chain and use generics.

Additional: Documentation on Interfaces

like image 134
Maximilian Burszley Avatar answered Feb 01 '23 11:02

Maximilian Burszley


Looks like you're implementing a basic factory method pattern:

public interface IVehicle {}

public class Car : IVehicle {}
public class Boat : IVehicle {}

public IVehicle CreateObjectType(JToken token)
{
    switch (token["type"].Value<string>())
    {
        case "Car":
            return new Car();
        case "Boat":
            return new Boat();
        default:
          throw new ArgumentOutOfRangeException(nameof(token));
    }
}
like image 32
Chris Pickford Avatar answered Feb 01 '23 11:02

Chris Pickford