C# - Variable types

Posted Jun 09, 2009 by Victorius / comments 0 comments / Print / Font Size Decrease font size Increase font size

I will teach you what kind of variables can you use in C#

Data types are used everywhere in a programming language like C#. Because it's a strongly typed language, you are required to inform the compiler about which data types you wish to use every time you declare a variable, as you will see in the chapter about variables. In this chapter we will take a look at some of the most used data types and how they work.

bool is one of the simplest data types. It can contain only 2 values - false or true. The bool type is important to understand when using logical operators like the if statement.

int is short for integer, a data type for storing numbers without decimals. When working with numbers, int is the most commonly used data type. Integers have several data types within C#, depending on the size of the number they are supposed to store.

string is used for storing text, that is, a number of chars. In C#, strings are immutable, which means that strings are never changed after they have been created. When using methods which changes a string, the actual string is not changed - a new string is returned instead.

char is used for storing a single character.

float is one of the data types used to store numbers which may or may not contain decimals.

Reference Type Variables

Reference type variables are made up of two parts: the reference on the stack and the object on the heap. The creation of the object and the reference to the object is commonly known as the instantiation of the object.

Example Reference variable

To declare a reference-type variable, the syntax used are:

string strMimico;city objToronto = null;object objGeneric;

Example Object variable

To create an object on the heap, we go through two steps, as follows:

1. Declare the variable reference.
2. Instantiate the object on the heap by calling the new operator.

City objMimico; //declare objMimico to be a reference to a an
// object of City type
objMimico = new City(); //call the constructor of the City class to return
// a reference that is stored in the objMimico reference


The two lines can be combined into one:

City objMimico = new City();

Rate this Article:

Be the first to rate me.


* You must be logged in order to leave comments, please login or join us.

Comments

No comments yet.



Bookmark and Share
Sign up for our email newsletter
Name:
Email: