简体   繁体   中英

what happens in memory when we declare a delegate in c#?

is delegate a method or class? if it is a method then how come we can instantiate it? only class can be instantiated so then the delegate must be class please help me I'm a bit confused due to this and where the delegate is stored in heap or stack?

Delegate is a Type Safe Pointer to point to your methods/functions. Which means you can pass the methods/functions as a parameter using delegates and it will be safe with the types also.

For more info check this link

A delegate is a reference type, same as a class, and as such is stored on the heap. Think of a delegate as an "stack" of references, that holds a function/method signatures.

A delegate is conceptually a type , but it's defined and acts as a class (with a MethodInfo property, an instance -or target-, and some methods -and runtime information, etc.-).

It defines a method signature. To instantiate it, you need to associate it with a method (so it's basically syntactic sugar to reference methods with an explicit signature).

It also has an Invoke method which is defined by the signature of the MethodInfo associated in runtime.

Delegate is just a type much like a class it allocates memory on the heap and an instance to call it on.and the delegate variable holds reference to this object.

Something like

        public class SomeAction : Delegate
        {
              private object _instance;
              private MethodInfo _method;
              public void Invoke()
              {
                //Invoke
              }
          }

Not exactly like this but something similar to it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM