Learning C# Part 2: Language Fundamentals

Written By: Kevin Jordan

- 07 Jul 2006 -

Description: This series aims to take a beginning programmer to an intermediate level in C#. Topics covered in Part 2 include: C# program structure, declaring and intializing variables, characters, strings, constants, enumeration, converting between types, and expressions and operators.

  1. C# Program Structure
  2. Declaring and Using Different Variable Types
  3. Constants and Enumeration
  4. Converting Variables and Using Expressions
  5. Aww Man... Not Homework

Constants

As you may have guessed, a constant variable is a variable whose value cannot be changed. You'll see these used a lot for math and physics, but can be used any time you don't want anyone to change a value. To declare a constant, just add const before the variable type and assign a value at the same time you declare it.

const int zero = 0;
const int phi = 1.61803D;

Enumeration

An enumeration is a user-defined type that specifies a group of named numeric constants. Basically you set up a group of items and then assign values to those variables. Using enumeration makes you code easier to read and it ensures that you're using valid values.

To create an enumeration type, use the enum keyword along with the name of the group. In the braces put a comma separated list of the values your enumeration can take. Here are a couple examples:

enum DayOfWeek
{
        Sunday,
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday
}
 
enum TimeInSeconds
{
        Second = 1,
        Minute = 60,
        Hour = 3600,
        Day = 86400
}

<< Previous

Next >>