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.
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
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With