sleath
sleath

Reputation: 881

C# Constants and Delegates

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.

Upvotes: 2

Views: 1071

Answers (5)

Dr. Rajesh Rolen
Dr. Rajesh Rolen

Reputation: 14285

Delegates: http://www.akadia.com/services/dotnet_delegates_and_events.html

Constants: There are two types of constants available in c#: Compile-time constants and runtime constants. They have different behaviors and using wrong one will cost you performance or correctness. so select proper constant type you are using for your project..

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

Upvotes: 1

Foxfire
Foxfire

Reputation: 5765

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.

Upvotes: 2

Abel
Abel

Reputation: 57217

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

Upvotes: 5

ChrisF
ChrisF

Reputation: 137198

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.

Upvotes: 1

Related Questions