C # constants and delegates
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.
source to share
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 toPI
or increase the allowable valueMAX_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).
source to share
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.
source to share
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
source to share