开发者

C# Constants and Delegates

开发者 https://www.devze.com 2022-12-08 01:19 出处:网络
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 s开发者_如何学运维een I can see other ways to program around them?Could an

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 s开发者_如何学运维een I can see other ways to program around them? Could any one tell me there true benefits for I've never used either.


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


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.


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.


C# Constants
constant versus readonly
C# Delegates


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号