Is this possible without reflection otherwise with reflection ? This is something very often used in PHP like in Wordpress.
Something in pseudo code:
if (exists(object.method)) {object.method}
or
try {object.method} finally {...}
Use .GetType().GetMethod()
to check if it exists, and then .Invoke()
it.
var fooBar = new FooBarClass();
var method = fooBar.GetType().GetMethod("ExistingOrNonExistingMethod");
if (method != null)
{
method.Invoke(fooBar, new object[0]);
}
Well, you could declare it in an interface, and then use:
IFoo foo = bar as IFoo;
if (foo != null)
{
foo.MethodInInterface();
}
That assumes you can make the object's actual type implement the interface though.
Otherwise you'd need to use reflection AFAIK.
(EDIT: The dynamic typing mentioned elsewhere would work on .NET 4 too, of course... but catching an exception for this is pretty nasty IMO.)
You could use dynamics and catch the Runtime exception:
dynamic d = 5;
try
{
Console.WriteLine(d.FakeMethod(4));
}
catch(RuntimeBinderException)
{
Console.WriteLine("Method doesn't exist");
}
Although it sounds more like a design problem.
Disclaimer
This code is not for use, just an example that it can be done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With