C Sharp/const

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Main Home

Basics
C# Tutorial Home
C# - Introduction to Visual Studio IDE
Introduction to C#
C# - Overview
C# - Statements
C# - Data Types
C# - Variables

C# - Operators
C# - Flow Control
C# - Variables II
C# - Functions and Methods
C# - Classes and Objects I
C# - Enumerations
C# - Dates and Times
C# - Random Numbers

Advanced
C# - Inheritance
C# - Polymorphism
C# - Garbage Collection
C# - Operator Overloading
C# - Encapsulation
C# - Properties
C# - Indexers
C# - Exceptions
C# - GUI
C# - Delegates
C# - Events
C# - Components
C# - Multithreading
C# - Regular Expressions
C# - Graphics and Multimedia
C# - Files and Streams
C# - XML
C# - Database, SQL and ADO.NET
C# - ASP.NET Web Forms and Web Controls
C# - Web Services
C# - Network Programming
C# - Datastructures and Collections
C# - Enumerations and Iterators
C# - .NET Assemblies
C# - CLR
C# - Visual Studio Debugger
C# - Namespaces
C# - Generics
C# - MS Intermediate Language
C# - Deploying Windows Application

Contents

[edit] The C# const keyword

The constant keyword makes a variable unchangable. PI = 3.14 it does not need to change. Constants cannot be placed on the left side of the expression, otherwise the compiler will issue errors when you attempt to compile your program. A const MUST be initialized with a value when it is declared.


[edit] Advantages of the C# const

  • Very good performance benefits
  • Good programming practice


[edit] Example 1:

This example will compute the area of a circle

using System;
class Program
{
    static void Main()
    {
        const float PI = 3.14f;
        float radius = 1.5f;
 
        Console.WriteLine(PI * radius * radius);
        Console.Read();
    }
}

Output:

7.065


[edit] Example 2:

This program will attempt to add two numbers.

using System;
class Program
{
    static void Main()
    {
        int number1 = 8;
        int number2 = 3;
        const int result = 0;
 
        result = number1 + number2;  //ERROR--const can't be on left side
 
        Console.WriteLine(result);
        Console.Read();
    }
}


Notice: This code will not compile because the const variable is on the left side