0

I have two objects that are found in two different classes but which have identical properties. I would like to do a function that argument in one of the object and to call this method with the object I want ( either one or the other)

This method can reach the properties of the one or the other one

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

1

Well it sounds like you should refactor the classes, as two classes with the same properties sounds like code duplication.

But if you need to do this (not knowing your problem) to do this you could use an Interface. So if we have two classes that store a name they could implement a interface like:

So the interface defines what the classes that implement it will do - like a contract.

 interface INameable
 {
     public string Name { get; set; }
 }

Then have your classes implement the interface:

class Pet : INameable
 {
    public string Name { get; set; }
 }


 class Person : INameable
 {
    public string Name { get; set; }
 }

Finally have a method which takes an object of the type of the interface:

public void MyMethod(INameable nameableObject)
{
     // do stuff
}

Now you can pass any object that implements INameable to a MyMethod call - in this case Pet or Person.

Tom
  • 480
  • 4
  • 13
1

Method can take two objects of different class?

I interpreted this as the following:

I need a method that can take objects that appear the same, regardless of implementation

Like I mentioned in my comment, you should use an interface -- consider the following:

public interface ICommonObject
{
    int Id { get; }
    string Name { get; }        
}

public class ObjectOne : ICommonObject
{
    int Id { get; }
    string Name { get; }

    public ObjectOne(int id, string name) 
    {
        Id = id;
        Name = name;
    }
}

public class ObjectTwo : ICommonObject
{
    int Id { get; }
    string Name { get; }

    public ObjectTwo(int id, string name) 
    {
        Id = id;
        Name = name;
    }
}

Then in your method, you take the ICommonObject interface as the parameter -- that way either implementation can be passed into it as an argument. Like so:

public class CommonLogic
{
    public void ActOnCommonObject(ICommonObject commonObject)
    {
        // TODO: do somthing with "commonObject"
    }
}

Now you could have an instance of either common object, so long as it implements that interface it is valid as an argument. The following code would be fine:

{
    var logic = new CommonLogic();

    var one = new ObjectOne();
    var two = new ObjectTwo();

    logic.ActOnCommonObject(one);
    logic.ActOnCommonObject(two);
}

You are left with an encapsulated snippet of logic that can act agnostic to the specific implementation, that can be easily unit tested.


For more details on interface implementation check out this MSDN article.

David Pine
  • 23,787
  • 10
  • 79
  • 107