C# Variables and (Primitive) Data Types: In this tutorial, we will learn about variables, how to create variables in C# and different data types that C# programming language supports.

A variable is a name of memory location. It is used to store data. Its value can be changed and it can to be reused commonly.

It is an approach to address memory location through symbol so that it can be easily identified.

A variable is a symbolic name given to a memory area. Variables are used to store data in a computer program.


How to declare variables in C#?

Here’s an example to declare a variable in C#.

int age;

In this example , a variable age of type int (integer) is declared and it can just store integer values.

We can assign a worth to the variable later in our program like such:

int age;
... ... ...
age = 24;

Notwithstanding, the variable can likewise be instated to some value during declaration. For instance,

int age = 24;

Here, a variable age of type int is declared and instated to 24 simultaneously.

Since, it’s a variable, we can change the value of variables too. For instance,

int age = 24;
age = 35;

Here, the value of age is changed to 35 from 24.


Variables in C# should be declared before they can be used. This implies, the name and sort of variables should be known before they can be assigned a value. This is the reason C# is known as a statically-typed language.

Once declared, the datatype of a variable can not be changed inside a scope. A scope can be thought as a block of code where the variable is noticeable or accessible to use. On the off chance that you don’t comprehend the previous statement, don’t stress we’ll learn over scopes in the later chapters.

For the present remember,we can not do the accompanying in C#:

int age;
age = 24;
... ... ...
float age;

Implicitly typed variables

On the other hand in C#, we can declare a variable without realizing its sort using var watchword. Such variables are called implicitly typed local variables.

Variables declared using var keyword must be initialized at the time of declaration.

var value = 5;

The compiler decides the type of variable from the value that is assigned to the variable. In the above example, value is of type int. This is equivalent to:

int value;
value = 5;

You can learn more about implicitly typed local variables.


Rules for Naming Variables in C#

There are certain standards we need to follow while naming a variable. The rules for naming a variable in C# are:

  1. The variable name can contain letters (uppercase and lowercase), underscore( _ ) and digits as it were.
  2. The variable name should begin with either letter, underscore or @ symbol. For instance,
Variable NamesRemarks
nameValid
subject101Valid
_ageValid (Best practice for naming private member variables)
@breakValid (Used if name is a reserved keyword)
101subjectInvalid (Starts with digit)
your_nameValid
your nameInvalid (Contains whitespace)

3. C# is case touchy. It means age and Age refers to 2 different variables.

4. A variable name should not be a C# watchword. For instance, if, for, using can not be a variable name. We will examine more about C# keywords in the next tutorial.


Best Practices for Naming a Variable

  1. Choose a variable name that bode well. For instance, name, age, subject makes well than n, an and s.
  2. Use camelCase notation (begins with lowercase letter) for naming local variables. For instance, numberOfStudents, age, and so forth
  3. Use PascalCase or CamelCase (begins with uppercase letter) for naming public member variables. For instance, FirstName, Price, and so on
  4. Use a main underscore (_) followed by camelCase notation for naming private member variables. For instance, _bankBalance, _emailAddress, and so on

You can learn more about naming conventions in C# here.

Try not to stress over public and private member variables. We will learn about them in later chapters.


C# Primitive Data Types

Variables in C# are broadly classified into two types: Value types and Reference types. In this tutorial we will examine about primitive (basic) data types which is a subclass of Value types.

Reference types will be covered in later tutorials. Nonetheless, on the off chance that you need to know more about variable types, visit C# Types and variables (official C# docs).

Boolean (bool)

• Boolean data type has two potential values: true or false

  • Default value: false

• Boolean variables are for the most part used to check conditions, for example, in if statements, loops, and so forth

For Example:

using System;
namespace DataType
{
    class BooleanExample
    {
        public static void Main(string[] args)
        {
            bool isValid = true;
            Console.WriteLine(isValid);
        }
    }
}

At the point when we run the program, the output will be:

True

Signed Integral

These data types hold integer values (both positive and negative). Out of the all out accessible bits, one bit is used for sign.

1. sbyte

• Size: 8 bits

• Range: – 128 to 127.

• Default value: 0

For instance:

using System;
namespace DataType
{
    class SByteExample
    {
        public static void Main(string[] args)
        {
            sbyte level = 23;
            Console.WriteLine(level);
        }
    }
}

At the point when we run the program, the output will be:

23

Try assigning values out of range i.e. less than -128 or greater than 127 and see what happens.


2. short

  • Size: 16 bits
  • Range: -32,768 to 32,767
  • Default value: 0

For instance:

using System;
namespace DataType
{
    class ShortExample
    {
        public static void Main(string[] args)
        {
            short value = -1109;
            Console.WriteLine(value);
        }
    }
}

At the point when we run the program, the output will be:

-1109

3.int

  • Size: 32 bits
  • Range: -231 to 231-1
  • Default value: 0

For instance:

using System;
namespace DataType
{
    class IntExample
    {
        public static void Main(string[] args)
        {
            int score = 51092;
            Console.WriteLine(score);
        }
    }
}

At the point when we run the program, the output will be:

51092

4. long

  • Size: 64 bits
  • Range: – 263 to 263-1
  • Default value: 0L [L toward the end address the worth is of long type]

For instance:

using System;
namespace DataType
{
    class LongExample
    {
        public static void Main(string[] args)
        {
            long range = -7091821871L;
            Console.WriteLine(range);
        }
    }
}

At the point when we run the program, the output will be:

-7091821871

Unsigned Integral

These data types just hold values equivalent to or greater than 0. We by and large use these data types to store values when we are certain, we will not have negative values.

1.byte

  • Size: 8 bits
  • Range: 0 to 255.
  • Default value: 0

For instance:

using System;
namespace DataType
{
    class ByteExample
    {
        public static void Main(string[] args)
        {
            byte age = 62;
            Console.WriteLine(level);
        }
    }
}

At the point when we run the program, the output will be:

62

2. ushort

  • Size: 16 bits
  • Range: 0 to 65,535
  • Default value: 0

For instance:

using System;
namespace DataType
{
    class UShortExample
    {
        public static void Main(string[] args)
        {
            ushort value = 42019;
            Console.WriteLine(value);
        }
    }
}

At the point when we run the program, the output will be:

42019

3.uint

  • Size: 32 bits
  • Range: 0 to 232-1
  • Default value: 0

For instance:

using System;
namespace DataType
{
    class UIntExample
    {
        public static void Main(string[] args)
        {
            uint totalScore = 1151092;
            Console.WriteLine(totalScore);
        }
    }
}

At the point when we run the program, the output will be:

1151092

4.ulong

  • Size: 64 bits
  • Range: 0 to 264-1
  • Default value: 0

For instance:

using System;
namespace DataType
{
    class ULongExample
    {
        public static void Main(string[] args)
        {
            ulong range = 17091821871L;
            Console.WriteLine(range);
        }
    }
}

At the point when we run the program, the output will be:

17091821871

Floating Point

These data types hold floating point value for example numbers containing decimal values. For instance, 12.36, – 92.17, and so on

1. float

  • Single-precision coasting point type
  • Size: 32 bits
  • Range: 1.5 × 10−45 to 3.4 × 1038
  • Default value: 0.0F [F toward the end address the worth is of buoy type]

For instance:

using System;
namespace DataType
{
    class FloatExample
    {
        public static void Main(string[] args)
        {
            float number = 43.27F;
            Console.WriteLine(number);
        }
    }
}

At the point when we run the program, the output will be:

43.27

2. double

For instance:

using System;
namespace DataType
{
    class DoubleExample
    {
        public static void Main(string[] args)
        {
            double value = -11092.53D;
            Console.WriteLine(value);
        }
    }
}

At the point when we run the program, the output will be:

-11092.53

Character (char)

  • It addresses a 16 bit unicode character.
  • Size: 16 bits
  • Default value: ‘\0’
  • Range: U+0000 (‘\u0000’) to U+FFFF (‘\uffff’)

For instance:

using System;
namespace DataType
{
    class CharExample
    {
        public static void Main(string[] args)
        {
            char ch1 ='\u0042';
            char ch2 = 'x';
            Console.WriteLine(ch1);
            Console.WriteLine(ch2);
        }
    }
}

At the point when we run the program, the output will be:

B
x

The unicode value of ‘B’ is ‘\u0042’, subsequently printing ch1 will print ‘B’.


Decimal

Decimal type has more precision and a smaller range as compared to floating point types (double and float). So it is appropriate for monetary calculations.

  • Size: 128 bits
  • Default value: 0.0M [M toward the end address the value is of decimal type]
  • Range: (- 7.9 x 1028 to 7.9 x 1028)/(100 to 28)

For instance:

using System;
namespace DataType
{
    class DecimalExample
    {
        public static void Main(string[] args)
        {
         decimal bankBalance = 53005.25M;
            Console.WriteLine(bankBalance);
        }
    }
}

At the point when we run the program, the output will be:

53005.25

The suffix M or m should be added toward the end in any case the value will be treated as a twofold and a mistake will be produced.


C# Literals

Let’s look at the following statement:

int number = 41;

Here,

int is a data type

number is a variable and

41 is a literal

Literals are fixed values that show up in the program. They don’t need any calculation. For instance, 5, false, ‘w’ are literals that show up in a program straightforwardly with no calculation.


Boolean Literals

  • true and false are the accessible boolean literals.
  • They are used to instate boolean variables.

For instance:

bool isValid = true;
bool isPresent = false;

Integer Literals

Integer literals are used to introduce variables of integer data types for example sbyte, short, int, long, byte, ushort, uint and ulong.

On the off chance that an integer literal finishes with L or l, it is of type long. For best practice use L (not l)

long value1 = 4200910L;
long value2 = -10928190L;

In the event that an integer literal beginnings with a 0x, it addresses hexadecimal value. Number with no prefixes are treated as decimal value. Octal and binary representation are not permitted in C#.

int decimalValue = 25;
int hexValue = 0x11c;// decimal value 284

Floating Point Literals

Floating point literals are used to introduce variables of float and double data types.

On the off chance that a floating point literal finishes with a suffix f or F, it is of type float. Additionally, on the off chance that it closes with d or D, it is of type double. On the off chance that neither of the suffix is available, it is of type double by default.

These literals contains e or E when expressed in scientific notation.

double number = 24.67;// double by default
float value = -12.29F;
double scientificNotation = 6.21e2;// equivalent to 6.21 x 102 i.e. 621

Character and String Literals

Character literals are used to instate variables of char data types.

Character literals are enclosed in single quotas. For instance, ‘x’,’p’, and so on

They can be addressed as character, hexadecimal escape sequence, unicode representation or integer values casted to char.

char ch1 = 'R';// character
char ch2 = '\x0072';// hexadecimal
char ch3 = '\u0059';// unicode
char ch4 = (char)107;// casted from integer

String literals are the collection of character literals.

They are enclosed in double quoates. For instance, “Hello”, “Simple Programming”, and so forth

string firstName = "Richard";
string lastName = " Feynman";

C# likewise supports escape sequence characters characters, for example,

CharacterMeaning
\’Single quote
\”Double quote
\\Backslash
\nNewline
\rCarriage return
\tHorizontal Tab
\aAlert
\bBackspace

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.