[ACCEPTED]-How to call a C# method only if it exists?-c#

Accepted answer
Score: 23

Well, you could declare it in an interface, and 6 then use:

IFoo foo = bar as IFoo;
if (foo != null)
{
    foo.MethodInInterface();
}

That assumes you can make the object's 5 actual type implement the interface though.

Otherwise 4 you'd need to use reflection AFAIK.

(EDIT: The 3 dynamic typing mentioned elsewhere would 2 work on .NET 4 too, of course... but catching 1 an exception for this is pretty nasty IMO.)

Score: 17

You could use dynamics and catch the Runtime 3 exception:

dynamic d = 5;
try
{
    Console.WriteLine(d.FakeMethod(4));
}
catch(RuntimeBinderException)
{
    Console.WriteLine("Method doesn't exist");
}

Although it sounds more like a 2 design problem.

Disclaimer
This code is not for use, just 1 an example that it can be done.

Score: 13

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]);
}

0

Score: 6

With the dynamic type in C# 4.0, you could do something 11 like this:

dynamic obj = GetDynamicObject();
if (obj != null && obj.GetType().GetMethod("DoSomething") != null)
{
    obj.DoSomething();
}

But the only way to tell if a 10 type has a method in the first place is 9 to use reflection; so the above approach 8 doesn't really buy you anything (you might 7 as well take the MethodInfo you get from calling GetMethod and 6 just Invoke it).

Edit: If you're open to trying to 5 call the method even when it's not there, then 4 Yuriy's answer is probably what you're looking for. My 3 original answer was a literal response to 2 the way you worded your question: "How 1 to call a C# method only if it exists."

Score: 3

I came across this looking for the same 2 answer but did not like any of the solutions.

here 1 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[] { });
Score: 2

You should revise existance first. MethodInfo[] myArrayMethodInfo = myType.GetMethods();

0

More Related questions