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 {...}
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.
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]);
}
FooBarClass
and knew it could change in the future to no longer include the method I am looking for.
Commented
Oct 7, 2019 at 18:08
With the dynamic
type in C# 4.0, you could do something like this:
dynamic obj = GetDynamicObject();
if (obj != null && obj.GetType().GetMethod("DoSomething") != null)
{
obj.DoSomething();
}
But the only way to tell if a type has a method in the first place is to use reflection; so the above approach doesn't really buy you anything (you might as well take the MethodInfo
you get from calling GetMethod
and just Invoke
it).
Edit: If you're open to trying to call the method even when it's not there, then Yuriy's answer is probably what you're looking for. My original answer was a literal response to the way you worded your question: "How to call a C# method only if it exists."
I came across this looking for the same answer but did not like any of the solutions.
here is mine:
//Invoke the refresh method if the datasource contains it
if (this.DataSource.GetType().GetMethod("Refresh") != null)
this.DataSource.GetType().GetMethod("Refresh").Invoke(this.DataSource, new object[] { });
You should revise existance first. MethodInfo[] myArrayMethodInfo = myType.GetMethods();
int Foo(string bar)
is not the same asdouble Foo(int bar, IDictionary<int, string> quux)
.