const value

In this chapter you will learn:

  1. Define constants with const keywords
  2. Local Constants

Constant value

The const modifier is used to declare fields or local variables that cannot be changed. These variables must be given initial values when they are declared. const implies static.

We can use const modifier to indicate that a field is a constant. The following Math class has a constant field PI.

class Math
{
    public const double PI = 3.14;
}
using System;//j  a  v a 2 s . com

class Constants
{
    public const int value1 = 33;
    public const string value2 = "Hello";
}
class MainClass
{
    public static void Main()
    {
        Console.WriteLine("{0} {1}", 
        Constants.value1, 
        Constants.value2);
    }
}

The code above generates the following result.

Local const value

const field can be used in a method.

The following code uses expressions to calculate and display the circumference of a circle.

class MainClass//from  j a  v a  2s .  c o  m
{

  public static void Main()
  {

    const double Pi = 3.14159;
    double diameter = 2.5;

    double circumference = Pi * diameter;

    System.Console.WriteLine("Circumference = " + circumference);

  }

}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is abstract class
Home » C# Tutorial » Class
Classes and Structs
Encapsulation
Class and Struct Accessibility
Members
Static Members
Class
Class instance variables
Class instance Methods
Class Inheritance
Class constructor
Default constructors
Parameters of constructors
Constructor overloading
Static Constructor
Destructor
Override destructor
new operator
Class field
Static Fields
Read only field
Field default value
const value
Abstract class
Static Class
Partial type
Methods
Method local variable
Method Overloading
Method overloading with ref and out
Type conversion and method overloading
Error in Method overloading
virtual methods
Override methods
Method Parameter
Pass parameters
ref parameters
out parameters
Variable parameter length
Optional parameters
Named parameters
static method
function Return
Recursive methods
Virtual methods and polymorphism
Cast
Shadow inherited members
Seal a member
this keyword
base keyword
base and name hiding
Access Specifiers
private
public
protected
internal
Indexer
String type indexer
Multidimensional indexer
Indexer overloading
Indexer to append
Indexer logic
Properties
Properties getter and setter
Accessibilities of properties
Automatic properties
Read only and write only property
Virtual properties
Abstract Properties
Static Properties
interface
interface implementation
Explicit interface implementation
Interface inheritance
Indexer in an interface
Interface Properties
struct and interface
virtual interface implementation
as operator
is operator
null reference
Nested classes
object class
ToString method
GetHashCode
Object initialization
Extension method
Struct Instances vs. Class Instances