Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constant field member in c#

Tags:

c#

hi all i am confused const long size =((long)int.Maxvalue+1)/4 how i interprate it... and what will happen when we define static const long size =((long)int.Maxvalue+1)/4... what is readonly member....

like image 871
Nishant Kumar Avatar asked Aug 27 '10 05:08

Nishant Kumar


People also ask

What are constants in C?

Constant is a value that cannot be changed during program execution; it is fixed. In C language, a number or character or string of characters is called a constant. And it can be any data type. Constants are also called as literals.

How do you declare a constant in C?

The const keyword Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

What are the three constants used in C?

There are various types of constants in C. It has two major categories- primary and secondary constants. Character constants, real constants, and integer constants, etc., are types of primary constants.

What is a constant variable?

A constant variable is one whose value cannot be updated or altered anywhere in your program. A constant variable must be initialized at its declaration.


1 Answers

const

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. For example;

public class MyClass
{
  public const double PI = 3.14159;
}

can't declare a member of class as "static const".

  • Because member variables declared as "const" are already "static".

PI 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;

  public MyClass()
  {
    PI = 3.14159;
  }
}
like image 162
Pranay Rana Avatar answered Sep 29 '22 18:09

Pranay Rana