Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a C# method only if it exists?

Tags:

c#

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 {...}
like image 557
user310291 Avatar asked Jan 31 '11 22:01

user310291


3 Answers

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]);
}
like image 80
mekb Avatar answered Nov 16 '22 12:11

mekb


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.)

like image 23
Jon Skeet Avatar answered Nov 16 '22 12:11

Jon Skeet


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.

like image 17
Yuriy Faktorovich Avatar answered Nov 16 '22 14:11

Yuriy Faktorovich