const and readonly perform a similar function on data members, but they have a few important differences.
Constants:
1. A constant members defined at compile time and they can't be changed at runtime
2. We must initialize when they are declared
Ex: public const double intrest=3.1056;
3.The above declared variable cannot be changed in the application anywhere else in the code as this will cause a compiler error.
Readonly :
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.
For example:
public class MyClass
{
public readonly double PI = 3.14159;
}
public class MyClass
{
public readonly double PI;
public MyClass()
{
PI = 3.14159;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment