- A constant member is defined at compile time and cannot be changed at runtime.
- Constants are declared as a field, using the
constkeyword and must be initialized as they are declared. - Since classes or structures are initialized at run time with the
newkeyword, 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
readonlymember can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. - Because a
readonlyfield can be initialized either at the declaration or in a constructor readonlyfields can have different values depending on the constructor used- A
readonlymember can hold a complex object by using thenewkeyword at initialization. readonlymembers cannot hold enumerations.readonlymembers are not implicitlystatic, and therefore thestatickeyword can be applied to areadonlyfield explicitly if required.
static Keyword
- Use of the
staticmodifier to declare astaticmember, 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
staticmethods and properties can only accessstaticfields andstaticevents- The
staticmodifier 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
staticclass member, use the name of the class instead of a variable name to specify the location of the member.

No comments:
Post a Comment