Home > Back-end >  Method that takes two different objects
Method that takes two different objects

Time:07-15

So i have two different objects, with different properties:

public class ModelA : IServices
    {
        public string Id { get; set; }
        public ServiceType ServiceType { get; set; } (Enum)
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public int Limit { get; set; }
        public int ChargePower { get; set; }
    }

public class ModelB : IServices
    {
        public string Id { get; set; }
        public ServiceType ServiceType { get; set; } (Enum)
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public int Power { get; set; }
    }

I have then created an Interface:

public interface IServices
    {
        public string Id { get; set; }
        public ServiceType ServiceType { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }

And i then use this interface as a input parameter on my method:

public async Task EditObject(IServices serviceObject)
        {
           
        }

My problem now is that if i call the method with e.g ModelA, i can only use the properties that is inside my Interface, and yes that makes sense. How can i make a method that can take both ModelA and ModelB and access the different properties inside these two objects? Is generics the way to go? or do i have to make two different methods? or am i on the correct way with an Interface? For instance i dont want ModelA to have ModelB:s property e.g "public int Power { get; set; }" Hope you understand my question, cheers!

CodePudding user response:

You can test, which class is it:

if (serviceObject is ModelA)
    ((ModelA)serviceObject).Limit = 5;

Or you can use Reflection:

PropertyInfo pi;    
if ((pi = x.GetType().GetProperty("Limit")) != null)
    pi.SetValue(x, 5);

CodePudding user response:

Well, a lot of ways

You can make a method overload

public async Task EditObject(ModelA serviceObject) { }
public async Task EditObject(ModelB serviceObject) { }

or you could access needed type through upcasting it

var iServiceVariable = (IServices)new ModelA();
var modelBVariable = iServiceVariable as ModelB;
Console.WriteLine($"Is iServiceVariable of ModelB type? {modelBVariable != null}");

Or you could implement different behavior in your models using the same interface(doesn't have to be IServices), but accessing them in EditObject through the same way (what's the point of interface otherwise?)

CodePudding user response:

If you want to do different things for multiple types, a fairly clean way to do it is by using a switch on the type:

switch(serviceObject)
{
    case ModelA modelA:
        modelA.Limit = 5;
        break;
    case ModelB modelB:
        modelB.Power = 2;
        break;
}
  • Related