Home

Using Variables

 

A Double-Word

 

Introduction

A double-word is a group of two consecutive Words. This means that a double-word combines 4 bytes or 32 bits. The bits, counted from right to left, start at 0 and end at 31.

The most right bit, bit 0, is called the Low Order bit or LO bit or LOBIT. The most left bit, bit 31, is called the High Order bit or HI bit or HIBIT. The other bits are called using their positions.

The group of the first 8 bits (from bit 0 to bit 7), which is the right byte, is called the Low Order Byte, or LO Byte. It is sometimes referred to as LOBYTE. The group of the last 8 bits (from bit 24 to bit 31), which is the left byte, is called the High Order Byte, or HI Byte or HIBYTE. The other bytes are called by their positions.

The group of the right 16 bits, or the right Word, is called the Low Order Word, or LO Word, or LOWORD. The group of the left 16 bits, or the left Word, is called the High Order Word, or HI Word, or HIWORD.  

The minimum binary number you can represent with a double-word is 0. The minimum decimal value of a double-word is 0. To find out the maximum decimal value of a word, you can use the base 2 formula giving a 1 value to each bit:

 
2n-1 230  229  228 227  226 225 224
etc 1,073,741,824 536,870,912 268,435,456 134,217,728 67,108,864 33,554,432 16,777,216
 
223 222 221 220 219 218 217 216
8,388,608 4,194,304 2,097,152 1,048,576 524,288 262,144 131,072 65,536
 
215 214 213 212 211 210 29 28
32,768 16,384 8,192 4,096 2,048 1,024 512 256
 
27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1

1*231+1*230+1*229 + 1*228 + 1*227 + 1*226 + 1*225 + 1*224 + 1*223 + 1*222 + 1*221 + 1*220 + 1*219 + 1*218 + 1*217 + 1*216 + 1*215 + 1*214 + 1*213 + 1*212 + 1*211 + 1*210 + 1*29 + 1*28 + 1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20

= 2,147,483,648 + 1,073,741,824 + 536,870,912 + 268,435,456 + 134,217,728 + 67,108,864 + 33,554,432 + 16,777,216 + 8,388,608 + 4,194,304 + 2,097,152 + 1,048,576 + 524,288 + 262,144 + 131,072 + 65,536 + 32,768 + 16,384 + 8,192 + 4,096 + 2,048 + 1,024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1

= 4,286,578,708

The minimum hexadecimal value you can store in a double-word is 0x00000000000000000000000000000000 which is the same as 0x0. To find out the maximum hexadecimal number you can represent with a word, replace every group of 4-bits with an f or F:

1111 1111 1111 1111 1111 1111 1111 1111
f f f f f f f f
= 0xffffffff = 0Xffffffff = 0XFFFFFFFF = 0xFFFFFFFF

To declare a variable that can hold large values, you can use the var keyword and initialize the variable with the desired value. Here is an example:

using System;

class Exercise
{
    static void Main()
    {
        var Population = 72394475;

        Console.Write("Country Population: ");
        Console.WriteLine(Population);
    }
}

This would produce:

Country Population: 72394475
Press any key to continue . . .

Practical LearningPractical Learning: Using Unsigned Integers

  1. Start Microsoft Visual C#
  2. To create a new application, on the main menu, click File -> New -> Project...
  3. In the Templates section, click Console Application
  4. Change the Name to GeorgetownCleaningServices3 and click OK
  5. Change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace GeorgetownCleaningServices3
    {
        class Program
        {
            static void Main(string[] args)
            {
                byte Shirts;
                byte Pants;
                ushort OtherItems;
    
                Shirts = 4;
                Pants = 0;
                OtherItems = 3;
    
                Console.WriteLine("-/- Georgetown Cleaning Services -/-");
                Console.WriteLine("========================");
                Console.WriteLine("------------------------");
                Console.WriteLine("Item Type  Qty");
                Console.WriteLine("------------------------");
                Console.Write("Shirts      ");
                Console.WriteLine(Shirts);
                Console.Write("Pants       ");
                Console.WriteLine(Pants);
                Console.Write("Other Items ");
                Console.WriteLine(OtherItems);
                Console.WriteLine("========================");
                Console.WriteLine();
            }
        }
    }
  6. Execute the program to see the result 
  7. Close the DOS window

Signed Integers

A double-word is large enough to contain double the amount of data that can be stored in a word. This is equivalent to 32 bits or 4 bytes or 4,294,967,295. Therefore, a double-word is used for large numbers that would not fit in a word.

To use a variable that would hold quite large numbers, besides the var keyword, you can declare it using the int keyword. A variable declared as int can store values between –2,147,483,648 and 2,147,484,647 negative or positive, that can fit in 32 bits.

Here is an example:

using System;

class Exercise
{
    static void Main()
    {
	int CoordX;
	int CoordY;
	
	CoordX = 12;
	CoordY = -8;

	Console.Write("Cartesian Coordinate System: ");
	Console.Write("P(");
	Console.Write(CoordX);
	Console.Write(", ");
	Console.Write(CoordY);
	Console.WriteLine(")\n");
    }
}

When executed, the program would produce:

Cartesian Coordinate System: P(12, -8)

If you declare an integer variable using the var keyword and initialize it with a value lower than 2,147,484,647, the compiler concludes that the memory needed to store that variable is 32 bits:

If you declare an integer variable using the var keyword and initialize it with a value lower than 2,147,484,647, the compiler concludes that the memory needed to store that variable is 32 bits

When initializing an integral variable, instead of a decimal number, you can also initialize it with a hexadecimal value whose decimal equivalent is less than 2,147,484,647. Here is an example:

using System;

class Exercise
{
    static void Main()
    {
        var Number = 0xF0488EA;

        Console.Write("Number: ");
        Console.WriteLine(Number);
    }
}

This would produce:

Number: 251955434
Press any key to continue . . .

Unsigned Integers

If the variable must hold only positive natural numbers, you can declared it using the uint keyword. The uint keyword is used to identify a 32-bit positive integer whose value would range from 0 to 2,147,484,647. Here is an example:

using System;

class Exercise
{
    static void Main()
    {
	uint DayOfBirth;
	uint MonthOfBirth;
	uint YearOfBirth;
	
	DayOfBirth   = 8;
	MonthOfBirth = 11;
	YearOfBirth  = 1996;

	Console.WriteLine("Red Oak High School");
	Console.Write("Student Date of Birth: ");
	Console.Write(MonthOfBirth);
	Console.Write("/");
	Console.Write(DayOfBirth);
	Console.Write("/");
	Console.Write(YearOfBirth);
	Console.WriteLine();
    }
}

This would produce:

Red Oak High School
Student Date of Birth: 11/8/1996

Practical LearningPractical Learning: Using Unsigned Integers

  1. To use unsigned variables, change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace GeorgetownCleaningServices3
    {
        class Program
        {
            static void Main(string[] args)
            {
                byte Shirts;
                byte Pants;
                ushort OtherItems;
    
                uint OrderDay;
                uint OrderMonth;
                uint OrderYear;
    
                Shirts = 4;
                Pants = 0;
                OtherItems = 3;
                OrderDay = 15;
                OrderMonth = 7;
                OrderYear = 2002;
    
                Console.WriteLine("-/- Georgetown Cleaning Services -/-");
                Console.WriteLine("========================");
                Console.Write("Order Date: ");
                Console.Write(OrderMonth);
                Console.Write('/');
                Console.Write(OrderDay);
                Console.Write('/');
                Console.WriteLine(OrderYear);
                Console.WriteLine("------------------------");
                Console.WriteLine("Item Type  Qty");
                Console.WriteLine("------------------------");
                Console.Write("Shirts      ");
                Console.WriteLine(Shirts);
                Console.Write("Pants       ");
                Console.WriteLine(Pants);
                Console.Write("Other Items ");
                Console.WriteLine(OtherItems);
                Console.WriteLine("========================");
                Console.WriteLine();
            }
        }
    }
  2. Execute the program. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ========================
    Order Date: 7/15/2002
    ------------------------
    Item Type  Qty
    ------------------------
    Shirts      4
    Pants       0
    Other Items 3
    ========================
    
    Press any key to continue . . .
  3. Close the DOS window

A Quad-Word

 

Introduction

Sometimes you may want to store values that a double-word cannot handle. To store a very large number in a variable, you can consider a combination of 64 bits. The group can also be referred to as a quad-word. A quad-word is so large it can store numbers in the range of –9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.

If you declare an integer variable using the var keyword and initialize it with a value between 2,147,484,647 and 9,223,372,036,854,775,807, the compiler concludes that the memory needed to store that variable is 64 bits:

If you declare an integer variable using the var keyword and initialize it with a value between 2,147,484,647 and 9,223,372,036,854,775,807, the compiler concludes that the memory needed to store that variable is 64 bits

Long Integers

If you want to use a variable that can hold very large numbers that would require up to 64 bits, you can declare it using either the var or the long keyword.

In C++, the long data type is 32 bits while in C#, the long data type is 64 bits.

As stated previously, if you initialize the variable with a value lower than 2,147,484,647, the compiler would allocate 32 bits of memory for it. If you initialize the variable with a value between 2,147,484,647 and 9,223,372,036,854,775,807, the compiler would allocate 64 bits of memory for it. If the value is higher than 9,223,372,036,854,775,807, which is too large, the compiler would present an error:

As stated previously, if you initialize the variable with a value lower than 2,147,484,647, the compiler would allocate 32 bits of memory for it. If you initialize the variable with a value between 2,147,484,647 and 9,223,372,036,854,775,807, the compiler would allocate 64 bits of memory for it. If the value is higher than 9,223,372,036,854,775,807, which is too large, the compiler would present an error

This means that you should limit the values assigned to integral variables to 64 bits, which is very significant.

Here is an example that uses the long data type:

using System;

class Exercise
{
    static void Main()
    {
        var CountryArea = 5638648;

        Console.Write("Country Area: ");
        Console.Write(CountryArea);
        Console.Write("km2\n");
    }
}

This would produce:

Country Area: 5638648km2
Press any key to continue . . .

As mentioned for other integral types, you can initialize a long variable with a hexadecimal value.

Although the long data type is used for large number, it mainly indicates the amount of space available but you do not have to use the whole space. For example, you can use the long keyword to declare a variable that would hold the same range of numbers as the short, the int, or the uint data types. If you declare a variable as long but use it for small numbers that don't require 64 bits, the compiler would allocate the appropriate amount of space to accommodate the values of the variable. Consequently, the amount of space made available may not be as large as 64 bits. If you insist and want the compiler to reserve 64 bits, when assigning a value to the variable, add an L suffix to it. Here is an example that uses space of a long data type to store a number that would fit in 32 bits:

using System;

class NumericRepresentation
{
    static void Main()
    {
	long CountryArea;
		
	CountryArea = 5638648L;

	Console.Write("Country Area: ");
	Console.Write(CountryArea);
	Console.Write("km2\n");
    }
}

Therefore, keep in mind that an int, a uint, a short, or a ushort can fit in a long variable.

Unsigned Long Integers

You can use a combination of 64 bits to store positive or negative integers. In some cases, you will need a variable to hold only positive, though large, numbers. To declare such a variable, you can use the ulong data type. A variable declared as ulong can handle extremely positive numbers that range from 0 to 18,446,744,073,709,551,615 to fit in 64 bits.

 

Real Numbers

 

Introduction

A real number is a number that displays a decimal part. This means that the number can be made of two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel:

Regional

On both sides of the Decimal Symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines how much precision the number offers.

Floating-Point Numbers

The integers we have used so far have the main limitation of not allowing decimal values. C# provides floating values that would solve this problem. The most fundamental floating variable is declared with the float keyword. A variable declared a float can store real numbers that range from ±1.5 × 10−45 to ±3.4 × 1038 with a precision of 7 digits in 32 bits. Here is an example:

using System;

class NumericRepresentation
{
    static void Main()
    {
	float Distance;
    }
}

Double-Precision Numbers

When a variable is larger than the float can handle and requires more precision, you should declare it using either the var or the the double keyword. Here is an example:

using System;

class Exercise
{
    static void Main()
    {
        var Number = 62834.9023;

        Console.Write("Number: ");
        Console.WriteLine(Number);
    }
}

This would produce:

Number: 62834.9023
Press any key to continue . . .

A variable declared as double uses 64 bits to store very large numbers ranging from ±5.0 × 10−324 to ±1.7 × 10308 with a precision of 15 or 16 digits. Because the double data type provides a better result with a better precision than the float, whenever you declare a variable using either the var or the float keyword and assign it a value, the compiler allocates 64 bits to store the values of the variable. If you insist on the variable being treated as float, when assigning it a value, add an F suffix to the value. Here is an example:

using System;

class NumericRepresentation
{
    static void Main()
    {
	float Distance;
		
	Distance = 248.38F;

	Console.Write("Distance = ");
	Console.Write(Distance);
	Console.WriteLine("km\n");
    }
}

This would produce:

Distance = 248.38km

Remember that if you declare the variable as var and want to treat it as a value with single precision, add an F suffix to the value assigned to it. Here is an example:

using System;

class Exercise
{
    static void Main()
    {
        var  Number = 62834.9023F;

        Console.Write("Number: ");
        Console.WriteLine(Number);
    }
}

On the other hand, if you want a value to be treated with double-precision, add a D suffix to it. Here is an example:

using System;

class Exercise
{
    static void Main()
    {
        var  Number = 62834.9023D;

        Console.Write("Number: ");
        Console.WriteLine(Number);
    }
}

Practical LearningPractical Learning: Using a Double-Precision Variable

  1. To use a double-precision value, change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace GeorgetownCleaningServices3
    {
        class Program
        {
            static void Main(string[] args)
            {
                byte Shirts;
                byte Pants;
                ushort OtherItems;
    
                uint OrderDay;
                uint OrderMonth;
                uint OrderYear;
    
                double MondayDiscount;
    
                Shirts = 4;
                Pants = 0;
                OtherItems = 3;
                OrderDay = 15;
                OrderMonth = 7;
                OrderYear = 2002;
                MondayDiscount = 0.25D; // 25%
    
                Console.WriteLine("-/- Georgetown Cleaning Services -/-");
                Console.WriteLine("========================");
                Console.Write("Order Date: ");
                Console.Write(OrderMonth);
                Console.Write('/');
                Console.Write(OrderDay);
                Console.Write('/');
                Console.WriteLine(OrderYear);
                Console.WriteLine("------------------------");
                Console.WriteLine("Item Type  Qty");
                Console.WriteLine("------------------------");
                Console.Write("Shirts      ");
                Console.WriteLine(Shirts);
                Console.Write("Pants       ");
                Console.WriteLine(Pants);
                Console.Write("Other Items ");
                Console.WriteLine(OtherItems);
                Console.WriteLine("------------------------");
                Console.Write("Monday Discount: ");
                Console.Write(MondayDiscount);
                Console.WriteLine('%');
                Console.WriteLine("========================");
                Console.WriteLine();
            }
        }
    }
  2. Execute the application to see the result:
     
    -/- Georgetown Cleaning Services -/-
    ========================
    Order Date: 7/15/2002
    ------------------------
    Item Type  Qty
    ------------------------
    Shirts      4
    Pants       0
    Other Items 3
    ------------------------
    Monday Discount: 0.25%
    ========================
    
    Press any key to continue . . .
  3. Close the DOS window

Decimal

The decimal data type can be used to declare a variable that would hold significantly large values that can be stored in a combination of 128 bits. You declare such a variable using the decimal keyword. The values stored in a decimal variable can range from ±1.0 × 10−28 to ±7.9 × 1028 with a precision of 28 to 29 digits. Because of this high level of precision, the decimal data type is suitable for currency values.

After declaring a decimal variable, you can initialize it with a natural number. To indicate that the variable holds a decimal value, when initializing it, add an M suffix to its value. Here is an example:

using System;

class NumericRepresentation
{
    static void Main()
    {
	decimal HourlySalary;
		
	HourlySalary = 24.25M;

	Console.Write("Hourly Salary = ");
	Console.WriteLine(HourlySalary);
	Console.WriteLine();
    }
}

This would produce:

Hourly Salary = 24

As seen in previous sections and this one, when declaring and initializing a real variable, the suffix you give to its assigned value indicates to the compiler the actual type of value and the type of memory that would be allocated for the variable:

  • If the value receives an F suffix, it is considered a floating point number with single precision
     
    If the value receives an F suffix, it is considered a floating point number with single precision
  • If the value receives a D suffix, it is considered a floating point number with double precision
     
    If the value receives an D suffix, it is considered a floating point number with double precision
  • If the value receives an M suffix, it is considered a large decimal number
     
    If the value receives an M suffix, it is considered a large decimal number

 

Practical LearningPractical Learning: Using Decimal Values

  1. To use decimal variables, change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace GeorgetownCleaningServices3
    {
        class Program
        {
            static void Main(string[] args)
            {
                byte Shirts;
                decimal  PriceOneShirt;
                byte Pants;
                decimal PriceAPairOfPants;
                ushort OtherItems;
                decimal PriceOtherItems;
    
                uint OrderDay;
                uint OrderMonth;
                uint OrderYear;
    
                double MondayDiscount;
    
                Shirts = 5;
                PriceOneShirt = 0.95M;
                Pants = 2;
                PriceAPairOfPants = 1.95M;
                OtherItems = 3;
                PriceOtherItems = 4.55M;
                OrderDay = 15;
                OrderMonth = 7;
                OrderYear = 2002;
                MondayDiscount = 0.25D; // 25%
    
                Console.WriteLine("-/- Georgetown Cleaning Services -/-");
                Console.WriteLine("========================");
                Console.Write("Order Date: ");
                Console.Write(OrderMonth);
                Console.Write('/');
                Console.Write(OrderDay);
                Console.Write('/');
                Console.WriteLine(OrderYear);
                Console.WriteLine("------------------------");
                Console.WriteLine("Item Type  Qty Unit Price");
                Console.WriteLine("------------------------");
                Console.Write("Shirts      ");
                Console.Write(Shirts);
                Console.Write("     ");
                Console.WriteLine(PriceOneShirt);
                Console.Write("Pants       ");
                Console.Write(Pants);
                Console.Write("     ");
                Console.WriteLine(PriceAPairOfPants);
                Console.Write("Other Items ");
                Console.Write(OtherItems);
                Console.Write("     ");
                Console.WriteLine(PriceOtherItems);
                Console.WriteLine("------------------------");
                Console.Write("Monday Discount: ");
                Console.Write(MondayDiscount);
                Console.WriteLine('%');
                Console.WriteLine("========================");
                Console.WriteLine();
            }
        }
    }
  2. Execute the program. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ========================
    Order Date: 7/15/2002
    ------------------------
    Item Type  Qty Unit Price
    ------------------------
    Shirts      5     0.95
    Pants       2     1.95
    Other Items 3     4.55
    ------------------------
    Monday Discount: 0.25%
    ========================
    
    Press any key to continue . . .
  3. Close the DOS window

Accessory Data Types

 

Strings

A string is an empty space, a character, a word, or a group of words that you want the compiler to consider "as is", that is, not to pay too much attention to what the string is made of, unless you explicitly ask it to. This means that, in the strict sense, you can put in a string anything you want.

Primarily, the value of a string starts with a double quote and ends with a double-quote. An example of a string is "Welcome to the World of C# Programming!". You can include such a string in Console.Write() to display it on the console. Here is an example:

using System;

class Exercise
{
    static void Main()
    {
	Console.WriteLine("Welcome to the World of C# Programming!");
    }
}

This would produce:

Welcome to the World of C# Programming!
Press any key to continue . . .

Sometimes, you will need to use a string whose value is not known in advance. Therefore, you can first declare a string variable. To do this, use either the var or the string keyword followed by a name for the variable. The name will follow the rules we defined above. When declaring a string variable, you can initialize it with an empty space, a character, a symbol, a word, or a group of words. The value given to a string must be included in double-quotes. Here are two examples:

using System;

class Exercise
{
    static void Main()
    {
        var Team = "Real Madrid";
        string Country = "Guinée Equatoriale";

        Console.WriteLine("Welcome to the World of C# Programming!");
        Console.Write("Team:    ");
        Console.WriteLine(Team);
        Console.Write("Country: ");
        Console.WriteLine(Country);
        Console.WriteLine();
    }
}

This would produce:

Welcome to the World of C# Programming!
Team:    Real Madrid
Country: Guinée Equatoriale

Press any key to continue . . .

Practical Learning Practical Learning: Using Strings

  1. To use strings, change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace GeorgetownCleaningServices3
    {
        class Program
        {
            static void Main(string[] args)
            {
                string CustomerName;
                string CustomerHomePhone;
    
                byte Shirts;
                decimal  PriceOneShirt;
                byte Pants;
                decimal PriceAPairOfPants;
                ushort OtherItems;
                decimal PriceOtherItems;
    
                uint OrderDay;
                uint OrderMonth;
                uint OrderYear;
    
                double MondayDiscount;
    
                CustomerName = "Gregory Almas";
                CustomerHomePhone = "(301) 723-4425";
                Shirts = 5;
                PriceOneShirt = 0.95M;
                Pants = 2;
                PriceAPairOfPants = 1.95M;
                OtherItems = 3;
                PriceOtherItems = 4.55M;
                OrderDay = 15;
                OrderMonth = 7;
                OrderYear = 2002;
                MondayDiscount = 0.25D; // 25%
    
                Console.WriteLine("-/- Georgetown Cleaning Services -/-");
                Console.WriteLine("========================");
                Console.Write("Customer:   ");
                Console.WriteLine(CustomerName);
                Console.Write("Home Phone: ");
                Console.WriteLine(CustomerHomePhone);
                Console.Write("Order Date: ");
                Console.Write(OrderMonth);
                Console.Write('/');
                Console.Write(OrderDay);
                Console.Write('/');
                Console.WriteLine(OrderYear);
                Console.WriteLine("------------------------");
                Console.WriteLine("Item Type  Qty Unit Price");
                Console.WriteLine("------------------------");
                Console.Write("Shirts      ");
                Console.Write(Shirts);
                Console.Write("     ");
                Console.WriteLine(PriceOneShirt);
                Console.Write("Pants       ");
                Console.Write(Pants);
                Console.Write("     ");
                Console.WriteLine(PriceAPairOfPants);
                Console.Write("Other Items ");
                Console.Write(OtherItems);
                Console.Write("     ");
                Console.WriteLine(PriceOtherItems);
                Console.WriteLine("------------------------");
                Console.Write("Monday Discount: ");
                Console.Write(MondayDiscount);
                Console.WriteLine('%');
                Console.WriteLine("========================");
                Console.WriteLine();
            }
        }
    }
  2. Execute the program. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ========================
    Customer:   Gregory Almas
    Home Phone: (301) 723-4425
    Order Date: 7/15/2002
    ------------------------
    Item Type  Qty Unit Price
    ------------------------
    Shirts      5     0.95
    Pants       2     1.95
    Other Items 3     4.55
    ------------------------
    Monday Discount: 0.25%
    ========================
    
    Press any key to continue . . .
  3. Close the DOS window

Dates and Times

A date is a unit that measures the number of years, months, or days elapsed in a specific period. A time is a unit that counts the number of seconds that have elapsed since midnight of the day considered. Although dates and times are large subjects that would require a detailed study, at this time, we will consider them in simple terms.

To declare a variable that would hold date or time values, use the DateTime data type.

using System;

class NumericRepresentation
{
    static void Main()
    {
	DateTime DateHired;
    }
}

The .NET Framework sets its starting periodic date to January 1, 0001 at midnight (12:00:00 or 0:00 AM). If not assigned a specific value (in future lessons, we will learn that this is equivalent to declaring a variable using the default constructor), the variable is initialized to 1/1/0001 at midnight.

Objects

The object data type is used to declare a variable whose type is not primarily defined and can be any of the other data types we have introduced. After creating an object variable, you can use its value as you see fit. For example, you can enter the variable in the parentheses of Console.Write() or Console.WriteLine() to display it in the console window. Here is an example:

using System;

class Exercise
{
    static void Main()
    {
        var EmployeeName = "Ernestine Lamb";
        object Address = "10244 Lockwood Drive";

        Console.Write("Employee Name: ");
        Console.WriteLine(EmployeeName);
        Console.Write("Home Address:  ");
        Console.WriteLine(Address);
        Console.WriteLine();
    }
}

This would produce:

Employee Name: Ernestine Lamb
Home Address:  10244 Lockwood Drive

Press any key to continue . . .

A variable declared with object can embrace almost any value. This means that, when initializing the variable, you can use any of the types of values we have seen so far. Here are examples:

using System;
class Program
{
    static void Main()
    {
        object PropertyNumber = "293749";
        object PropertyType = 'S';
        object Stories = 3;
        object Bedrooms = 4;
        object Value = 425880;

        Console.WriteLine("=//= Altair Realty =//=");
        Console.WriteLine("Properties Inventory");
        Console.Write("Property #:    ");
        Console.WriteLine(PropertyNumber);
        Console.Write("Property Type:  ");
        Console.WriteLine(PropertyType);
        Console.Write("Stories:        ");
        Console.WriteLine(Stories);
        Console.Write("Bedrooms:       ");
        Console.WriteLine(Bedrooms);
        Console.Write("Market Value:   ");
        Console.WriteLine(Value);
    }
}

This would produce:

=//= Altair Realty =//=
Properties Inventory
Property #:    293749
Property Type:  S
Stories:        3
Bedrooms:       4
Market Value:   425880
Press any key to continue . . .

Constants

 

Custom Constants

Suppose you intend to use a number such as 39.37 over and over again. Here is an example:

using System;

class Exercise
{
    static void Main()
    {
	double Meter, Inch;
		
	Meter = 12.52D;
	Inch = Meter * 39.37D;
        Console.Write(Meter);
        Console.Write("m = ");
        Console.Write(Inch);
        Console.WriteLine("in\n");
    }
}

Here is an example of running the program:

12.52m = 492.9124in

If you use this 39.37 many times in your program, at one time, you may make a mistake and type it as 3937 or 3.937 or else. Consider the following program:

using System;

class Exercise
{
    static void Main()
    {
        double Meter, Inch;

        Meter = 12.52D;
        Inch = Meter * 39.37;
        Console.Write(Meter);
        Console.Write("m = ");
        Console.Write(Inch);
        Console.WriteLine("in\n");

        Meter = 12.52D;
        Inch = Meter * 3.937;
        Console.Write(Meter);
        Console.Write("m = ");
        Console.Write(Inch);
        Console.WriteLine("in\n");

        Meter = 12.52D;
        Inch = Meter * 393.7;
        Console.Write(Meter);
        Console.Write("m = ");
        Console.Write(Inch);
        Console.WriteLine("in\n");
    }
}

This would produce:

12.52m = 492.9124in

12.52m = 49.29124in

12.52m = 4929.124in

Because of mistakes in the way to represent the number, the same calculation produces different results. To make sure that this is unlikely, you can instead use a variable that holds the value. Then, when you need that value, you can access the variable instead of the value itself. A number such as 39.37 is called a constant.

A constant is a value that never changes such as 244, "ASEC Mimosa", 39.37, or True. These are constant values you can use in your program any time. You can also declare a variable and make it a constant; that is, use it so that its value is always the same.

To create a constant, type the const keyword to its left. When declaring a constant, you must initialize it with an appropriate value. Here is an example:

const double ConversionFactor = 39.37D;

Once a constant has been created and it has been appropriately initialized, you can use its name where the desired constant would be used. Here is an example of a constant variable used various times:

using System;

class Exercise
{
    static void Main()
    {
        const double ConversionFactor = 39.37D;
        double Meter, Inch;

        Meter = 12.52D;
        Inch = Meter * ConversionFactor;
        Console.Write(Meter);
        Console.Write("m = ");
        Console.Write(Inch);
        Console.WriteLine("in\n");

        Meter = 12.52D;
        Inch = Meter * ConversionFactor;
        Console.Write(Meter);
        Console.Write("m = ");
        Console.Write(Inch);
        Console.WriteLine("in\n");

        Meter = 12.52D;
        Inch = Meter * ConversionFactor;
        Console.Write(Meter);
        Console.Write("m = ");
        Console.Write(Inch);
        Console.WriteLine("in\n");
    }
}

This would produce:

12.52m = 492.9124in

12.52m = 492.9124in

12.52m = 492.9124in

Notice that, this time, the calculation is more accurate. Also, this time, if you mistype the name of the variable in an operation, you would receive a compiler error, giving you the time to fix it.

To initialize a constant variable, the value on the right side of the assignment operator "=" must be a constant or a value that the compiler can determine as constant. Instead of using a known constant, you can also assign it another variable that has already been declared as constant.

Built-in Constants

There are two main categories of constants you will use in your programs. You can create your own constant as we saw above. The C# language also provides various constants. Some constants are part of the C# language. Some other constants are part of the .NET Framework. Before using a constant, of course, you must first know that it exists. Second, you must know how to access it. A constant that is part of the C# language can be accessed anywhere in your code. Those constant are normally defined in the System namespace. Other constant are defined in various appropriate namespaces.

null: The null keyword is a constant used to indicate that a variable doesn't hold a known value

PI: PI is a constant used as the ratio of the circumference of a circle to its diameter. PI is defined in Math. To use it, you would type Math.PI.

 

 

Previous Copyright © 2008-2011 FunctionX Next