Can we pass generic object using object class

68 views Asked by At
public class Sample1
{
    public void setdata(Object obj)
    {
    //...Do the logic based on object type
    }
}

i want this method (setdata) to be reusable across.i.e. I want to pass object of different types/classes

public class Sample2 : Sample1
{
    public void dosomething()
    {
    Sample1 a = new Sample1();
    Sample2 b= new Sample2();
    a.setdata(b);
}
}

.Is this simply possible with Object class or is it compulsory to use generics //to get it done . if yes , how?please help.Thanks !

1

There are 1 answers

1
nvoigt On

Yes, you can do that:

public static class ObjectExtensions
{
    public static void SetData(this object that, object other)
    {
        // now here it gets tricky and probably really bad OOD
    }
}

This would result in every object and class derived from object (that covers all reference types) to expose a public method called SetData.

string s = new string();
Window w = new Window();

s.SetData(w);

However, whatever you do inside that method is probably extremly bad software design and should probably be solved differently based on what you actually want to do.