C# Constants and Delegates-Collection of common programming errors


  • xxmrlnxx

    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.


  • Foxfire

    Delegates are an absolute must-have if you add events to your class or are doing anything asynchroneous (There are several other good reasons to have delegates). Benefits is that it is a very flexible approach.

    Constants help you to prevent “Magic Numbers”. Aka provide a central place where you can specify constant data that is semantically identical. Their benefit is that they incur absolutely no performance or memory overhead.


  • Abel

    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).


  • ChrisF

    Constants should be used for values like pi (3.14159…). Using them means that your code reads sensibly:

    double circumference = radius * 2.0 * PI;
    

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


  • Rajesh Rolen- DotNet Developer