Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
C# - What is the point of declaring Delegates?

I'm trying to understand Delegates in C#. I'm not too deep down the rabbit hole yet; as far as I know they are just pointers. I made the mistake of trying to apply JavaScript logic to C# when trying to understand them originally (everything is let or const) however soon realized there was no way to assign methods. So I understand why we need Delegates, my question is:

Why do we declare them?

Instead of:

public delegate void Pointer(String text);
Pointer p = SomeMethod;

Why not just do:

var p = SomeMethod;

???

I'm sure there must be some advanced things I don't know yet but I just can't see why you would ever need to declare them the first way???

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Most of the time, I find that Action and Func suffice. One reason you might want to declare them is to pass them back into an event handler. For instance,

public delegate void MyEventHandler(object sender, MyEventArgs e);

And then you would follow that up with

public event MyEventHandler OnEvent;

This would let you subscribe to that event, presumably with custom arguments in MyEventArgs. In this case, you couldn't rely on var, though you could use Action to achieve a similar result without declaring the delegate prototype:

public event Action<object, MyEventArgs> OnEvent;

Why would you ever declare the delegate? For me, it mostly comes down to consistency. Declaring the delegate gives you one place where you can change your code if the signature ever changes, which also, in my opinion, makes your code more readable.

over 4 years ago · Santiago Trujillo Report

0

Delegate types are commonly needed if you want to give the caller of a function the possability to calucalte something while the execution of the method (e.g. List<T>.ForEach uses a delegate for calling a user defined function for each element).

A delegate type is defined the following:
<access modifier> deleage <function header>

Using this delegate assures the compiler, that the function takes the right parameters and returns a value of the right type. Of course this could be checked at runtime but this isn't the approach of C#. This is in contrast to dynamic typed languages (JavaScript, Python, ...), which might have the possability to just check at runtime whether the function matchs the requirements.

So you are right, it is theoretically not necessery but C#, Java and other static typed languages just require a definition of the function somewhere.

C# is static typed. So every object must have a known datatype. The var keyword just makes the compiler decide the datatype instead of the programmer.

But as it is in your example, you don't have to write a custom delegate for every thing, there are some standart delegates like Action and Function. If your function matchs one of those predefined interfaces you can assign them using the type explicitly (writing the datatype before the variable name) or implicitly just as you did with the var keyword.

over 4 years ago · Santiago Trujillo Report

0

Why do we declare them?

We declare everything in C#. Well, apart from dynamic (but even then, it's a front for a dictionary).

Why not just do var p = SomeMethod;

Try doing that on a .net framework project; you'll get an error "cannot assign method group to implicitly typed local variable". Some of the advice you find floating round on the internet predates the invention of the .net you're using and so targets older patterns of doing things

I just can't see why you would ever need to declare them the first way?

If you look at the evolution of C# over the time it's always trying to find ways of allowing one to more compactly/neatly express their intent. What started out as quite a verbose syntax for (insert operation like "declaring a property" here) comes down in characters over time, usually because the bits that people use a lot become wearisome to keep typing out (even with propfull-tab-tab) or even read

Since the introduction of generics it's been possible to use Action<...> and Func<...> instead of declaring one's own delegate types, but delegate preceded generics so for a good while we used the delegate keyword a lot.

Those years of "doing it this way" builds up an inertia of documentation/teaching that doesn't change overnight. No one sees C# 10 come out and immediately go through all their old blogs and throw away/rewrite the advice to do X some old way that the newest C# makes simpler; they instead write another blog post about the new features which usually helps people transition if they're used to the old way.

It also stands to reason that if you're learning about delegates then a web search would bring up a tutorial that mentions the word. Such a tutorial would perhaps most sensibly start off at some very base level of "how we do it" because it ties in with the rest of the concepts of the language - here's how we declare a class that represents a person, here's how we declare a delegate that represents an operation that takes an int and returns a string - for a tutorial to start out at the highest level of convenience that C# offers and say "just say var p = SomeMethod, and make sure to omit () so you don't call the method, and C# will do the rest of the trickery needed to make an object that refers to the method" doesn't teach a lot about what goes on under the hood.

As a relative newcomer without that background knowledge of how it was to relate to, you're relating it to other languages, which can be problematic (especially something fairly fast-n-loose like JavaScript) but in recent versions of C# you absolutely can do as you propose (var p = SomeMethod). If you land a job working with some N year old code base you'll probably find delegate ... in there somewhere so having the familiarity with it you've acquired will help you read it even if you cannot migrate it to a more modern incarnation..

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!