Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an object is a delegate

Tags:

c#

.net

delegates

In .NET, Is there a way to check whether an object is of a delegate type?

I need this because I'm logging the parameters of method calls, and I want to print "(delegate)" for all parameters which are actions or functions.

like image 933
Ilya Kogan Avatar asked Apr 28 '11 14:04

Ilya Kogan


People also ask

Is delegate a class in C#?

Delegates are the library class in System namespace. These are the type-safe pointer of any method. Delegates are mainly used in implementing the call-back methods and events. Delegates can be chained together as two or more methods can be called on a single event.

What is delegate in C# example?

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.

How to call delegate in C#?

Delegates can be invoke like a normal function or Invoke() method. Multiple methods can be assigned to the delegate using "+" or "+=" operator and removed using "-" or "-=" operator. It is called multicast delegate. If a multicast delegate returns a value then it returns the value from the last assigned target method.

What is a function delegate?

A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate.


1 Answers

Sure, same as with any other type:

if (foo is Delegate)

Or for a type:

if (typeof(Delegate).IsAssignableFrom(t))
like image 110
Jon Skeet Avatar answered Sep 30 '22 08:09

Jon Skeet