Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Constants and Delegates

Tags:

c#

.net

asp.net

I've seen delgates and constants before in code but when and where are the appropiate times to use these? The uses that I've seen I can see other ways to program around them? Could any one tell me there true benefits for I've never used either.

like image 929
sleath Avatar asked Mar 12 '26 12:03

sleath


1 Answers

I'd like to emphasize the difference between const and readonly in C#, even though you don't ask, it can be of importance:

  1. A const variable is replaced by its literal value when you compile. That means, if you change the value of it (i.e., add more digits to PI, or increase allowed MAX_PROCESSORS), and other components use this constant, they will not see the new value.
  2. A readonly variable cannot be changed either, but is never replaced by its literal value when you compile. When you update your reference, other components of your application will see this update immediately and do not need to be recompiled.

This difference is subtle but very important as it can introduce subtle bugs. The lesson here is: only use const when you are absolutely sure the value will never change, use readonly otherwise.

Delegates are a placeholder (blueprint, signature) of a method call. I consider them the interface declaration of a method. A delegate variable is of the type of a delegate. It can be used as if it were the method (yet it can point to different implementations of the same method signature).

like image 120
Abel Avatar answered Mar 15 '26 02:03

Abel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!