Home

Introduction to C#

 

Variables

 

Introduction

A variable is information used in an application but that can change from one moment to another. Before using a variable, you must declare it.

The general formula used to declare a variable is:

TypeOfVariable VariableName;

If you want to declare more than one variable of the same type, you can declare each with the type, its name, and its semi-colon. The formula to follow would be:

TypeOfVariable Variable1; TypeOfVariable Variable2; TypeOfVariable Variable_n;

An alternative is to use one data type followed by the names of variables that would share this type. The names of variables must be separated by commas. The formula to follow would be:

TypeOfVariable Variable1, Variable2, Variable_n;

If you want to declare different variables that use different data types, you can declare each with the type, its name, and its semi-colon, on the same line. The formula to follow would be:

TypeOfVariable1 Variable1; TypeOfVariable2 Variable2; TypeOfVariable3 Variable3;

A better alternative is to declare each variable on its own line. This makes the program easier to read. The formula to follow would be:

TypeOfVariable1 Variable1;
TypeOfVariable2 Variable2;
TypeOfVariable3 Variable3;

Variables Names

When using the various necessary variables in your programs, you will need to identify each one of them. A variable is primarily recognized by its name.

The name of a variable:

  • Starts with an underscore “_” or a letter, lowercase or uppercase, such as a letter from a to z or from A to Z. Examples are Name, gender, _Students, pRice
  • Can include letters, underscore, or digits. Examples are: keyboard, Master, Junction, Player1, total_grade, _Score_Side1
  • Cannot include special characters such as !, %, ], or $
  • Cannot include an empty space
  • Cannot be any of the reserved words
  • Should not be longer than 32 characters (although allowed)

C# is case-sensitive; this means that CASE, Case, case, and Case are four completely different words.

Data Types

 

Variable Initialization

You can use the equal symbol (also called the assignment operator) to initialize a variable. To do that, after typing the name of the variable, type = followed by the desired value. The formula used would be:

TypeOfVariable VariableName = InitialValue;

Introduction to Data Types

We have mentioned that the syntax of declaring a variable was:

TypeOfVariable VariableName;

The TypeOfVariable factor lets the compiler know the amount of memory that will be needed for the variable. This TypeOfVariable is commonly called the data type.

If many different variables are using the same data type, you can declare them on the same line, separating two with a comma, except the last one that would end with a semi-colon. The formula to follow is:

DataType Variable1, Variable2, Variable3;

Practical LearningPractical Learning: Introducing Data Types Applications

  1. To create a new web site, launch Microsoft Visual Web Developer 2008 Express Edition
  2. On the main menu, click File -> New Web Site...
  3. Make sure ASP.NET Web Site is selected.
    Set the Language to Visual C#.
    In the Location box, accept the suggested name of the web site or change it to realestate1 and click OK
  4. Change the Default.aspx file as follows:
     
    <%@ Page Language="C#"
        AutoEventWireup="true"  
        CodeFile="Default.aspx.cs" 
        Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Altair Realtors</title>
    </head>
    <body>
    
    <%
        Response.Write("<h2>=//=  Altair Realty  =//=</h2>");
        Response.Write("<h3>=== Properties Inventory ===</h3>");
    %>
    
    </body>
    </html>
  5. To execute the application, on the main menu, click Debug -> Start Without Debugging

    Real Estate
  6. After viewing the page, return to your programming environment

Integers

 

Signed and Unsigned Numbers

An integer is a natural number typically used to count items. An integer is considered a "whole number" because it doesn't display a decimal fraction.

A variable is referred to as unsigned if it must hold only a positive number.

Bytes

The most fundamental number is represented by the byte data type. A byte is an unsigned number whose value ranges from 0 to 255. To declare such a variable, you can use the byte keyword.

If you want to use a small number but whose variable can hold either positive or negative values, you can declare it using the sbyte data type. A variable declared with sbyte can hold a value between -127 and 128, not more, not less.

Practical LearningPractical Learning: Declaring a Byte Variable

  1. To declare a byte variable, change the file as follows:
     
    <%@ Page Language="C#"
        AutoEventWireup="true"  
        CodeFile="Default.aspx.cs" 
        Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Altair Realtors</title>
    </head>
    <body>
    
    <%
        byte stories = 2;
    %>
    
    <%
        Response.Write("<h2>=//=  Altair Realty  =//=</h2>");
        Response.Write("<h3>=== Properties Inventory ===</h3>");
        Response.Write("<pre>Property:");
        Response.Write("<pre>Stories: " + stories.ToString() + "<pre>");
    %>
    
    </body>
    </html>
  2. Save the file
  3. Return to the browser and refresh to see the result:
     
    Real Estate
  4. Return to your programming environment

Short Variables

If you need to represent a number that is a little higher than the Byte can hold, you can declare it using the short keyword. Here is an example:

<%@ Page Language="C#" %>
<html>
<head>
<title>Active Exercise</title>
</head>
<body>

<h3>Active Exercise</h3>

<%
    short Pages = 424;
    
    Response.Write(Pages);

%>
</body>
</html>

A short variable can hold a natural number whose value ranges from -32768 to 32767. Based on this, it is important to note that a byte value can fit in a short. Therefore, it is normal to declare as short a variable that would hold even small numbers such as people's ages.

If you want the variable to hold only positive numbers, you can use the ushort data type. When using the ushort keyword, you can store numbers that range from 0 to 65535. If you assign either a negative number or a number higher than 65535, the number would not be truncated. You would receive an error. Consider the following example:

<%@ Page Language="C#" %>
<html>
<head>
<title>Active Exercise</title>
</head>
<body>

<h3>Active Exercise</h3>

<%
    ushort number = -424;
    
    Response.Write(number);

%>
</body>
</html>

Integral Variables

In some cases you may need a variable that holds a number larger than the short can carry. To declare such a variable, you can use the int keyword. The int data type is used for a variable whose value can range from –2,147,483,648 to 2,147,484,647. Here is an example:

<%@ Page Language="C#" %>
<html>
<head>
<title>Active Exercise</title>
</head>
<body>

<h3>Active Exercise</h3>

<p>Number: 
<%
    int number = 53911;
    
    Response.Write(number);

%>
</p>

</body>
</html>

It is important to note that, based on its range of values, an int variable can hold the same values as the byte or the short. Therefore, it is perfectly normal and sometimes preferable to use int for a variable intended to hold natural numbers.

By default, an int declared variable can hold either positive or negative values. If you want the variable to hold only positive numbers, you can type the uint keyword. Here is an example:

<%@ Page Language="C#" %>
<html>
<head>
<title>Active Exercise</title>
</head>
<body>

<h3>Active Exercise</h3>

<p>Number: 
<%
    uint number = 46082;
    
    Response.Write(number);

%>
</p>

</body>
</html>
 

Practical LearningPractical Learning: Declaring Integer Variables

  1. To use unsigned variables, change the file as follows:
     
    <%@ Page Language="C#"
        AutoEventWireup="true"  
        CodeFile="Default.aspx.cs" 
        Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Altair Realtors</title>
    </head>
    <body>
    
    <%
        byte stories = 2;
        uint bedrooms = 5;
        uint yearBuilt = 1962;
    %>
    
    <%
        Response.Write("<h2>=//=  Altair Realty  =//=</h2>");
        Response.Write("<h3>=== Properties Inventory ===</h3>");
        Response.Write("<pre>Property<pre>");
        Response.Write("<pre>Stories:    " + stories.ToString() + "<pre>");
        Response.Write("<pre>Bedrooms:   " + bedrooms.ToString() + "<pre>");
        Response.Write("<pre>Year Built: " + yearBuilt.ToString() + "<pre>");
    %>
    
    </body>
    </html>
  2. Save the and return to the browser to refresh it
  3. Return to your programming environment

Long Integers

While the int data type can hold significantly large numbers, you may still need a variable that can hold very large numbers. Such a variable can be declared using the long data type. Such a variable can hold a number that ranges from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Based on this, it is important to note that a long variable can hold a short or an int variable. Here is an example:

<%@ Page Language="C#" %>
<html>
<head>
<title>Active Exercise</title>
</head>
<body>

<h3>Active Exercise</h3>

<p>Number: 
<%
    long number = 46082;
    
    Response.Write(number);
%>
</p>

</body>
</html>
 

Practical LearningPractical Learning: Declaring Long Integers

  1. To declare a long variable, change the file as follows:
     
    <%@ Page Language="C#"
        AutoEventWireup="true"  
        CodeFile="Default.aspx.cs" 
        Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Altair Realtors</title>
    </head>
    <body>
    
    <%
        long propertyNumber = 490724;
        byte stories = 2;
        uint bedrooms = 5;
        uint yearBuilt = 1962;
    %>
    
    <%
        Response.Write("<h2>=//=  Altair Realty  =//=</h2>");
        Response.Write("<h3>=== Properties Inventory ===</h3>");
        Response.Write("<pre>Property #: " +
            propertyNumber.ToString() + "<pre>");
        Response.Write("<pre>Stories:    " + stories.ToString() + "<pre>");
        Response.Write("<pre>Bedrooms:   " + bedrooms.ToString() + "<pre>");
        Response.Write("<pre>Year Built: " + yearBuilt.ToString() + "<pre>");
    %>
    
    </body>
    </html>
  2. Save the file
  3. Return to the browser and refresh it

    Real Estate 
  4. Return to your programming environment

Characters

 

Symbolic Characters

A character is a symbol that can be a letter such as a, b, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, and z. It can also be a letter from A to Z. It can also be a digit such as 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. It can also by a special characters such as ` ~ # $ ! @ % ^ & * ( { [ ) } ] | \ : ; “ ‘ + - < _ ? > , / =. A character is really an integer whose value can range from -128 to 127.

To declare a character variable, you use the char keyword. Since a char variable represents one symbol, to initialize it, enclose the initial value in single quotes. Here is an example:

<%@ Page Language="C#" %>
<html>
<head>
<title>Active Exercise</title>
</head>
<body>

<h3>Active Exercise</h3>

<p>Number: 
<%
    char AlphaLetter = 'G';
    
    Response.Write(AlphaLetter);

%>
</p>

</body>
</html>

Practical LearningPractical Learning: Using Character Variables

  1. To use a character variable, change the file as follows:
     
    <%@ Page Language="C#"
        AutoEventWireup="true"  
        CodeFile="Default.aspx.cs" 
        Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Altair Realtors</title>
    </head>
    <body>
    
    <%
        long propertyNumber = 490724;
        char propertyType = 'S';
        byte stories = 2;
        uint bedrooms = 5;
        uint yearBuilt = 1962;
    %>
    
    <%
        Response.Write("<h2>=//=  Altair Realty  =//=</h2>");
        Response.Write("<h3>=== Properties Inventory ===</h3>");
        Response.Write("<pre>Property #: " +
            propertyNumber.ToString() + "<pre>");
        Response.Write("<pre>Property Type:  " +
                    propertyType.ToString() + "<pre>");
        Response.Write("<pre>Stories:    " + stories.ToString() + "<pre>");
        Response.Write("<pre>Bedrooms:   " + bedrooms.ToString() + "<pre>");
        Response.Write("<pre>Year Built: " + yearBuilt.ToString() + "<pre>");
    %>
    
    </body>
    </html>
  2. Save the file
  3. Return to the browser and refresh it

    Real Estate
  4. Return to your programming environment

The String: A List of Characters

A string is a group of characters considered as one unit, as opposed to a single character as we introduced above. To declare a variable that can hold a string, use the string data type. The value of the string must be included in double-quotes. Here is an example:

string Course = "Business Mathematics";

Practical LearningPractical Learning: Using Character Variables

  1. To use a character variable, change the file as follows:
    <%@ Page Language="C#"
        AutoEventWireup="true"  
        CodeFile="Default.aspx.cs" 
        Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Altair Realtors</title>
    </head>
    <body>
    
    <%
        string Address = "6808 Lilas Drive";
        string City = "Silver Spring";
        string State = "MD";
        string ZIPCode = "20904";
        
        long propertyNumber = 490724;
        char propertyType = 'S';
        byte stories = 2;
        uint bedrooms = 5;
        uint yearBuilt = 1962;
    %>
    
    <%
        Response.Write("<h2>=//=  Altair Realty  =//=</h2>");
        Response.Write("<h3>=== Properties Inventory ===</h3>");
        Response.Write("<pre>Property #: " +
            propertyNumber.ToString() + "<pre>");
        Response.Write("<pre>Address:        " + Address + "<pre>");
        Response.Write("<pre> " +
            City + ", " + State + " " + ZIPCode + "<pre>");
        Response.Write("<pre>Property Type:  " +
                    propertyType.ToString() + "<pre>");
        Response.Write("<pre>Stories:    " + stories.ToString() + "<pre>");
        Response.Write("<pre>Bedrooms:   " + bedrooms.ToString() + "<pre>");
        Response.Write("<pre>Year Built: " + yearBuilt.ToString() + "<pre>");
    %>
    
    </body>
    </html>
  2. Save the file
  3. Return to the browser and refresh it

    Real Estate
  4. Return to your programming environment

Decimal Numbers

 

Floating-Point Variables

The integers we have used so far don't allow decimal values. Floating-point numbers can solve this problem. To declare a variable that involves a decimal value, you can use the float keyword.

A float variable can hold a number that ranges from 3.4 x 10-38 to 3.4 x 1038. Besides, or instead of, float, you can use the Single data type to declare a variable that holds a simple decimal value.

Double-Precision Variables

One of the limitations of the float data type is that it provides less precision than required sometimes. The alternative is to use the double data type to declare a variable that would hold decimal numbers.

A double-precision variable declared with double can hold a decimal or fractional number that ranges from 1.7 x 10-308 to 1.7 x 10308. It is used for numbers that and/or are very large.

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.

Initializing a Real Number

Because the double data type provides a better result with a better precision than the float, whenever you declare a variable as float 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 or an F suffix to the value.

If you declare a double variable, when initializing it, to make sure the value is treated as double, type the d or the D suffix to the right of the value.

If you declare a variable using the decimal keyword, to indicate that the variable holds a decimal value, when initializing it, add an m or an M suffix to its value.

Practical LearningPractical Learning: Using a Single-Precision Variables

  1. To use a double-precision variable, change the file as follows:
     
    <%@ Page Language="C#"
        AutoEventWireup="true"  
        CodeFile="Default.aspx.cs" 
        Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Altair Realtors</title>
    </head>
    <body>
    
    <%
        string Address = "6808 Lilas Drive";
        string City = "Silver Spring";
        string State = "MD";
        string ZIPCode = "20904";
        
        long propertyNumber = 490724;
        char propertyType = 'S';
        byte stories = 2;
        float bathrooms = 3.5f;
        uint bedrooms = 5;
        uint yearBuilt = 1962;
        decimal marketValue = 652540M;
    %>
    
    <%
        Response.Write("<h2>=//=  Altair Realty  =//=</h2>");
        Response.Write("<h3>=== Properties Inventory ===</h3>");
        Response.Write("Property #: " +
            propertyNumber.ToString() + "<br />");
        Response.Write("Address:        " + Address + "<br />");
        Response.Write(" " +
            City + ", " + State + " " + ZIPCode + "<br />");
        Response.Write("Property Type:  " +
                    propertyType.ToString() + "<br />");
        Response.Write("Stories:    " + stories.ToString() + "<br />");
        Response.Write("Bedrooms:   " + bedrooms.ToString() + "<br />");
        Response.Write("Bathrooms:      " +
            bathrooms.ToString() + "<br />");
        Response.Write("Year Built: " + yearBuilt.ToString() + "<br />");
        Response.Write("Market Value:   " +
                marketValue.ToString() + "");
    %>
    
    </body>
    </html>
  2. Save the file
  3. Return to the browser and refresh it
     
    Real Estate
  4. Return to your programming environment

Previous Copyright © 2006-2016, FunctionX, Inc. Next