Sunday, November 1, 2009

Const ,Readonly, Static .....Have a Loo0ook

const Keyword

  • A constant member is defined at compile time and cannot be changed at runtime.
  • Constants are declared as a field, using the const keyword and must be initialized as they are declared.
  • Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure.
    • for example       public const double PI=3.14 
      • so we the value of PI will be constant through all the application and can't change it and if we try to change it, will give us compilation error 
readonly Keyword 
  • A read only member is like a constant in that it represents an unchanging value
  • The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared.
  • Because a readonly field can be initialized either at the declaration or in a constructor
  • readonly fields can have different values depending on the constructor used
  • readonly member can hold a complex object by using the new keyword at initialization.
  • readonly members cannot hold enumerations.
  • readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required.

static Keyword 
  • Use of the static modifier to declare a static member, means that the member is no longer tied to a specific object.
  • This means that the member can be accessed without creating an instance of the class
  • static methods and properties can only access static fields and static events
  • The static modifier can be used with classes, fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types other than classes.
  • To access a static class member, use the name of the class instead of a variable name to specify the location of the member.

No comments:

Post a Comment