C# Variable, Constants, Identifiers & Data types

C# Variables

Data values are kept in containers called variables.

distinct sorts of variables (specified with distinct keywords) exist in C#. For instance:

  • int – holds whole numbers, or integers, such as 123 or -123, without decimals.
  •   double – stores floating point numbers, with decimals, such as 19.99 or -19.99
  •  char – keeps track of single characters like “a” or “B.” Single quotations around the values of char.
  • string  – Text like “Hello World” is stored. Double quotations surround string values.
  • bool – holds values in the true or false state.

Declaring (Creating) Variables

You need to provide the type and give a variable a value in order to create it:

type variableName = value;

where variableName is the name of the variable (like x or name) and type is a C# type (like int or string). Values are assigned to the variable using the equal sign.

Take a look at the following example to learn how to construct a variable that will hold text:

 

Example

Make a variable called name of type string and put “Sravani” in it:
 
   string name = “sravani”;
   Console.WriteLine(name);
 

Take a look at the following example to learn how to build a variable that should hold a number:

Example

Make a variable of type int named myNum, and give it the value 15:
 
      int myNum = 15;
      Console.WriteLine(myNum);
 

It is also possible to declare a variable without first assigning a value, then assign the value afterwards:

Example

     int myNum;

      myNum = 15;

       Console.WriteLine(myNum);

Note that if you assign a new value to an existing variable, it will overwrite the prior value:

Example

Put myNum’s value back to 20:

 

     int myNum = 15;
      myNum = 20;
      Console.WriteLine(myNum);
 

Other Types

An example of declaring variables of different types:

 int myNum = 5;

 double myDoubleNum = 5.99D;

 char myLetter = ‘D’;

 bool myBool = true;

 string myText = “Hello”;

Later on in this chapter, you will discover more about data types.

Constants

You can put the const keyword in front of the variable type if you don’t want other people (or yourself) to overwrite existing values.

Declaring the variable as “constant” will make it read-only and unchangeable:

Example 

 const int myNum = 15;

 myNum = 20;// error

When you want a variable to always hold the same value—so that you or others won’t make mistakes in your code—    you can use the const keyword. PI (3.14159…) is one example that is frequently used to refer to as a constant. It should be noted that a constant variable cannot be declared without a value assigned. If you do, a mistake will happen: A value must be entered into a const field.

Display Variables

When displaying variable values in the console window, the WriteLine() function is frequently utilized.

Use the + symbol to merge text with a variable:

Example

string name = “gkits;

console.writeLine(“Hello” + name);

Additionally, you can add a variable to another variable by using the + symbol:

string firstName = “gkits”;

string Last = “student”;

string fullName = firstName + lastName;

Console.WriteLine(fullName);

The + symbol functions as a mathematical operator for numeric values (note that we are using int (integer) variables here):

Example

int X = 5;
int Y = 6;
Console.WriteLine(X + Y);
 
From the above example, you may anticipate:
  • x stores the value 5
  • y stores the value 6
  • Next, we show the value of x + y, which is 11, using the WriteLine() method.

Declare Many Variables

When declaring multiple variables of the same type, separate them using commas:

Example

int x, y, z ;

 x = 5, y = 6, z =50;

Console.WriteLine(x + y + z);
 

C# Identifiers

Every C# variable needs to have a distinct name.
We refer to these distinct names as identifiers.
 

Identifiers can be more descriptive names like age, sum, or totalVolume, or they can be simple names like x and y.

Note: To write comprehensible and maintainable code, it is advised to use descriptive names:

Example

// good
      int minutesPerHour =  60 ;
// OK, but not so easy to understand what m actually is
int m = 60;
 
Here are the general guidelines for naming variables:
  • Letters, numbers, and the underscore character (_) can all be found in names.
  • Names have to start with an underscore or letter.
  • Names cannot begin with a space and must begin with a lowercase letter.
  • Case matters when naming variables (“myVar” and “myvar” are distinct variables).
  • Reserved terms cannot be used as names (such as C# keywords like int or double).

Data Types

The variables chapter explains that a variable in C# needs to be a certain type of data:
 

Example

       int myNum = 5;               // integer (whole number)
      double myDoubleNum = 5.99D;  // floating point number
      char myLetter = ‘D’;         // character
      bool myBool = true;          // boolean
      string myText = “Hello”;     // string
 
The size and type of variable values are specified by a data type.
 
In addition to preventing errors and saving time and memory, using the appropriate data type for each variable will improve the readability and maintainability of your code. The most typical kinds of data are:
 
Data TypeSizeDescription
int4 bytesStores whole numbers from -2,147,483,648 to 2,147,483,647
long8 bytesStores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float4 bytesStores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double8 bytesStores fractional numbers. Sufficient for storing 15 decimal digits
bool1 bitStores true or false values
char2 bytesStores a single character/letter, surrounded by single quotes
string2 bytes per characterStores a sequence of characters, surrounded by double quotes

Numbers

Two categories exist for different number types:

Whole numbers, whether positive or negative (like 123 or -456), are stored as integer types without digits. Int and long are acceptable types. The numerical value determines the type to utilize.

Numbers having one or more decimals and a fractional portion are represented by floating point types. Double and float are acceptable types.
 
The most popular numeric types in C# are double (for floating point values) and int (for whole numbers), despite the fact that there are many more numeric types as well. Still, as you read on, we’ll go over each one in detail.

Integer Types

Int

The full numbers from -2147483648 to 2147483647 can be stored in an int data type. When we construct variables with a numeric value, the int data type is generally the preferred data type—this is also the case in our course.

Example

int myNum = 100000;
Console.WriteLine(myNum);

Long

Whole numbers between -9223372036854775808 and 9223372036854775807 can be stored in the long data type. When int is too small to store the value, this is utilized. Keep in mind that a “L” should be used to finish the value:

Example

      long myNum = 15000000000L;
      Console.WriteLine(myNum);

Floating Point Types

Whenever you need a number with a decimal, like 9.99 or 3.14515, you should use a floating point type.

Fractional numbers can be stored in the float and double data types. Keep in mind that a “F” should be used to terminate the value for floats and a “D” for doubles.

Float Example

       float myNum = 5.75F;
      Console.WriteLine(myNum);

Double Example

     double myNum = 19.99D;
      Console.WriteLine(myNum);

Should you use double or float?

The number of digits that can follow the decimal point in a floating point value is indicated by its precision. Whereas double variables have a precision of roughly 15 decimal places, float variables only have six or seven. For the majority of computations, it is therefore safer to utilize double.

Scientific Numbers

A scientific number with a “e” to represent the power of ten can also be a floating point number:

Example

      float f1 = 35e3F;
      double d1 = 12E4D;
      Console.WriteLine(f1);
      Console.WriteLine(d1);

Booleans

The bool keyword is used to specify a boolean data type, which can only accept the values true or false:
Example
      bool isCSharpFun = true;
      bool isFishTasty = false;
      Console.WriteLine(isCSharpFun);   // Outputs True
      Console.WriteLine(isFishTasty);   // Outputs False    
 
The main application for boolean values is in conditional testing, which is covered in greater detail in a later chapter.
Characters
 A single character can be stored using the char data type. The character needs to have single quotes around it, such as “A” or “c”:

Example

char myGraade = “B”;

console.WriteLine(myGrade);

Strings

A text string is stored as a sequence of characters using the string data type. Double quotations must enclose string values:

Example

      string greeting = “Hello World”;
      Console.WriteLine(greeting);