0

I have 3 classes :-

public Class Example1
{
  public void Method1()
  {
  }
  public void Method2()
  {
  }
}

public Class Example2
{
  public void Method3()
  {
  }
  public void Method4()
  {
  }
}

public Class CompletelyDifferentClass
{
  public void DifferentMethod(Example1/Example2 obj)
  {
      obj.Method1(); //if object is passed for Example1
      obj.Method3(); //if object is passed for Example2
  }
}

If we see CompletelyDifferentClass and public DifferentMethod(Example1/Example2 obj)

I want DifferentMethod to get parameter as any time I can send Example1 object or Example2 object. If Example2 object is sent , it should enable methods for Example2 like obj.Method3();

It is not fixed that which class's object I am going to send as a parameter to that method.

How can I write a code for DifferentMethod

C Sharper
  • 8,284
  • 26
  • 88
  • 151
  • If you don't know the type of the object passed as an argument at compile time (typed `object`) then you need to read about [Reflection](https://msdn.microsoft.com/en-us/library/mt656691.aspx). – InBetween Mar 29 '17 at 10:14
  • 2
    Use the `is` operator or the `as` operator, perhaps? But it sounds like overloads would be better. This sounds like a bit of an X-Y problem, and it's not clear what it has to do with ASP.NET. – Jon Skeet Mar 29 '17 at 10:14
  • [And many more](https://www.google.com/search?q=method+parameter+different+types+c%23) – Patrick Hofman Mar 29 '17 at 10:15

1 Answers1

0

You can write a base class and then inherit your child classes from that base class.

Then you can pass any type of child class inheriting from the same class. Like

public class myBase{

}

public class A: myBase{

}

public class B: myBase{

}

public static void myFunction(myBase obj){

}

And you can pass any child class to ur base class like

myFunction(A);
myFunction(B);

Another way is to use method overloading. You can write same functions with same signature. This is a good read for function overloading

Also you can take in object as a parameter type. Even better, perhaps, would be to use generics:

void MyFunction<T>(T parm) {

}

Hope it helps :)

Community
  • 1
  • 1
Muhammad Qasim
  • 1,622
  • 14
  • 26