C # constants and delegates

I've seen delgates and constants before in code, but when and where are the right times to use them? What uses have I seen, do I see other ways of programming around them? Can anyone tell me what true benefits I have never used.

+2


source to share


5 answers


Delegates are absolutely necessary if you are adding events to your class or making anything asynchronous (there are several other good reasons for delegates). The advantage is that it is a very flexible approach.



Constants help prevent magic numbers. Aka's provide a central place where you can specify persistent data that is semantically identical. Their advantage is that they have absolutely no performance or memory.

+2


source


I would like to highlight the difference between const

and readonly

in C #, even if you don't ask, it might be important:

  • On compilation, variable A const

    is replaced with its literal value. This means that if you change its value (i.e. add more digits to PI

    or increase the allowable value MAX_PROCESSORS

    ) and other components use this constant, they will not see the new value.
  • It is not possible to change the variable A readonly

    , but it is not replaced by its literal value on compilation. When you update your link, other components of your application will see the update immediately and do not need to be recompiled.


This difference is subtle, but very important as it can introduce subtle errors. Lesson here: only use const

when you are absolutely sure the value will never change, use readonly

otherwise
.

Delegates are the placeholder (plan, signature) of the method call. I see them as method interface declarations. The delegate variable is of the delegate type. It can be used as if it were a method (but it can point to different implementations of the same method signature).

+5


source


Constants should be used for values ​​like pi (3.14159 ...). Using them means your code reads intelligently:

double circumference = radius * 2.0 * PI;

      

it also means that if the value of the constant changes (obviously not for pi!), you only need to change the code in one place.

+1


source


+1


source


Conference participants: http://www.akadia.com/services/dotnet_delegates_and_events.html

Constants: There are two types of constants in C #: Compile-time constants and run-time constants. They have different behaviors and using the wrong one will cost you productivity or correctness. so choose the correct persistent type you are using for your project.

http://dotnetacademy.blogspot.com/2011/09/constants-in-net.html

+1


source







All Articles