Reputation: 588
Using C#, lets say I have these classes:
classZero
classOne
classTwo
class classZero and classOne have a public function named "Hello()".
how can i creat a new function (in any class) that takes a unknown class as a paramenter and then run the function "Hello" on this unknown class, if it exists?
in sebdo code this would look something like this:
function runHelloIfPossible(anyclass aclass):
if aclass contains function Hello:
aclass.Hello()
if in my case the anyclass argument where any of classZero or classOne the function Hello would run.
Upvotes: 0
Views: 674
Reputation: 23228
You can use type pattern matching with switch
statement for that (it's available from C# 7)
public void RunHelloIfPossible(object anyObject)
{
switch (anyObject)
{
case classZero zero:
zero.Hello();
break;
case classOne one:
one.Hello();
break;
}
}
Example of the usage
RunHelloIfPossible(new classOne());
If both classes implement the same interface (lets say IHello
) or base class, the code above can be simplified to
if (anyObject is IHello hello)
{
hello.Hello();
}
Upvotes: 1
Reputation:
the key word dynamic can be used, please see below codes.
class Program
{
static void Main(string[] args)
{
var class0 = new ClassZero();
var class1 = new ClassOne();
var class2 = new ClassTwo();
var class3 = new ClassWithoutHello();
class2.DynamicCall(class0);
class2.DynamicCall(class3);
Console.ReadLine();
}
}
public class ClassZero
{
public void Hello()
{
Console.WriteLine("say hello from Class Zero");
}
}
public class ClassOne
{
public void Hello()
{
Console.WriteLine("say hello from Class One");
}
}
public class ClassWithoutHello
{
}
public class ClassTwo
{
public void DynamicCall(dynamic input)
{
Console.WriteLine("calling input from Class Two");
if ((input is ClassZero) || (input is ClassOne))
{
input.Hello();
}
else
{
Console.WriteLine("this type does NOT support hello method");
}
}
}
Upvotes: 1
Reputation: 1331
public interface IHello
{
void Hello();
}
public class Zero: IHello
{
public void Hello()
{
}
//...
}
...
void RunHelloIfPossible(object obj)
{
if (obj is IHello ih)
{
ih.Hello();
}
}
Upvotes: 1