Tuesday, April 18, 2017

Lesson 4: C# Types and Variables

C# Types

The .NET framework includes a common type system (CTS) that is supported by all .NET languages, including C#; this allows cross platform integration of code – meaning a single application can be written using multiple languages such as C#, Visual C++ and Visual Basic. The types in CTS are commonly referred as common types and are divided into two broad categories: value types and reference types.

Value Types
The contents of a value type are simply a value. For instance,
           
int x = 100;

In the memory address in which x is associated the value 100 is stored. When placed in memory, value types contain their own copy of data.

Reference Types

Reference types holds the memory address in which the actual data is stored; the memory address associated with a reference type doesn’t contain the actual data. Instead, the address in which the actual data is stored is stored in reference type variable.
The following shows how memory is represented for value types and reference types.
int yearOfBirth = 2009;
String nameOfChild = “Shallom”;


Value Types Revisited

Value types are the common types needed by most application, and are often called fundamental or primitive data types. In C#, the primitive data types are also further divided int two categories – struct types and enum types. The following figure shows the hierarchy of value types in C#.



                                                           
Literal Values

The value of a variable is changeable; however, literals cannot be altered. Literals are the numbers, characters, and combination of characters used in your program. They can be assigned and used in and expression, and their value remains the same.
The commonly used primitive datatypes in C# are listed in the following table given below.


Variables

A variable is a named memory location where a value of a particular data type is stored; when a variable is declared, a memory address is allocated for the data item in your program. Before a variable is used in your C# program, it must be first declared, and declaring a variable in C# follows the following syntax.
                            

Where type is one of the data types in C# (it could a reference type or primitive data type), and identifier is a name that follows valid identifier naming rule in C#.
At the time a variable is declared or created, it can be initialized to a value and this process is programmatically referred as compile-time initialization.
An instance of compile time initialization follows the following syntax:
 Example: 

                

                  
Note: when the variable is going to be used for some kind of arithmetic operations, it is a good programming practice to initialize it to 0.
The following are some further instances of compile-time initialization.
            int age = 18;
            int sum = 0;

            double totalRevene = totalR;

Converting Data Types

Converting from one datatype to another is programmatically referred as casting. Two common types of casting are – implicit and explicit.

Implicit Casting

If a conversion between primitive data types does not result losing of information, casting can be done implicitly. For example, since an int – a 32 bit integer type – can accommodate a byte, an 8 bits integer type, conversion from byte to int is done without losing any information implicitly.

// Implicit conversion. bignNum long can
// hold any value an int can hold
 int num = 2147483647;
 long bigNum = num

The following shows an example of the supported implicit data type conversion in C#:


Explict Casting

Explicit conversion is also called casting; it requires a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Such conversions as numeric conversion to a type that has less precision or a smaller range, and conversion of a base‐class instance to a derived class are typical conversions that require explicit casting.

Note: We will see what base classes and child classes are in the topic of inheritance.

// explicit casting:  x double
// is converted to i int
 double x = 5870.25;
 int i = (int)x;  // the value of i is 5870

The following program demonstrates how variables are declared, initialized and used in such simple mathematical operations as addition and division.


/*
 * Author: Temesghen Tekeste
 * Basic operation of C# Variables
 * */
using System;
namespace variables
{
    class Program
    {
        static void Main(string[] args)
        {
            //declaring and assigning an int 
            int age = 27;
            //declaring and assigning double  
            double price = 20.05;
            double weight = 78.36;
            // Adding two integer values 
            int a = 10;
            int b = 200;
            int result = a + b;
            //calculating speed  
            double distance = 150.50;
            double time = 2;
            double speed = distance / time;
            //outputing int values 
            Console.WriteLine("Age: {0}, sum of {1} and {2} is {3}",
              age, a, b, result);
            //outputing double values 
            Console.WriteLine("Price: {0}, speed of a car that travels" +
               " {1} km in {2} hour is {3} km/hr",
               price, distance, time, speed);
            Console.WriteLine("Press any key to exit ...");
            Console.ReadKey();
        }
    }

}

Download Source Code

Output:



No comments:

Post a Comment