C# Variables: Primitive and Non-primitive Types

In this article, I will be discussing C# variables and the difference between primitive and non-primitive types. This post is just one of many posts covering various topics in C# as I continue towards my goal of learning the C# programming language. If you have done any developing with any other programming language, then variables should not be anything new to you as they are essential for any productive language.

C# is a strongly typed language which means that variables must be explicitly defined. The compiler will throw an error if a value assigned or being assigned is not the data type specified. An example of this is a variable assigned a number cannot hold text later on in the program. Also, a variable defined as an integer cannot be assigned a string.

For those of you that do not know, a variable is nothing more than a name given to a storage location in memory. The name you give your variables is called the identifier. Identifiers cannot start with a number, have white spaces in them, or be one of the reserved keywords in C#.  I will further discuss naming conventions for your variables in a later post.

In C# there are 2 types of variables, primitive types and non-primitive types.

Primitive Types

C# primitives are also called value types and predefined in the .NET framework. Primitive types can be assigned a value directly. The value assigned is stored on the stack as opposed to the heap.

Listed below are some of the most used primitive types and their value range.

Short Name Value Range
bool true or false
byte 0 to 255
short -32,768 to 32,767
int  -2,147,483,648 to 2,147,483,647
long  -9223372036854775808 to 9223372036854775807
float  -3.402823e38 to 3.402823e38
double  -1.79769313486232e308 to 1.79769313486232e308
decimal  ±1.0 × 10e−28 to ±7.9 × 10e28
char  Unicode symbols used in text

 Declaring Primitive Type Variables

// Declaring variables

// Integer declared but not initialized
int myInteger1;

// Integer declared and initialized to a value of 5
int myInteger2 = 5;

// Char declared and initialized to 'a'
char myChar = 'a';

// String declared and initialized to 'Hello World'
string myString = "Hello World";

Non-primitive Types

Now that we have covered primitive types it is time to discuss non-primitive types. Non-primitive are also called reference types meaning the identifier has a reference to a location in memory which stores the variable.  The reason for this is all non-primitive types are derived from the object class and not predefined in C#.

Classes

Classes are blueprints from which we create objects. I will be covering classes in much more detail in a later post but for now, I will show how to declare a class.

public class Vehicle
{
	public int Id;
	public short Year;
	public string Make;
	public string Model;

	public void DriveVehicleForward()
	{
		// Logic to move vehicle forward
	}
}

Here we can see that we have a class called Vehicle. The Vehicle class has a few field in it that describe a vehicle. It also has a method named DriveVehicleForward that in real life would contain the logic for moving the Vehicle object forward. Now let’s say we want to create a new vehicle object from the class above.

Vehicle myVehicle = new Vehicle();
myVehicle.Id = 1;
myVehicle.Year = 1999;
myVehicle.Make = "Chevy";
myVehicle.Model = "Corvette";

Console.WriteLine(myVehicle.Make); // Output: Chevy

// Let's drive our new vehicle forward
myVehicle.DriveVehicleForward();

As you can see in the above example, we can create a new object called myVehicle and set its properties to a 1999 Chevy Corvette. We were also able to drive our new vehicle forward using the DriveVehicleForward method.

Structs

Structs are like classes and allow you to create objects from them. The difference is, Structs are more lightweight than a class. For this reason, we use structs when we need to create a bunch of objects to keep in memory. An example of this is a list of books.

Check out the example below where I show you how to create a struct for our book objects. I then create a book from that struct.

struct Book
{
	public int Id;
	public short PublicationYear;
	public string Title;
	public string AuthorName;
}

Book myBook = new Book();
myBook.Id = 1;
myBook.PublicationYear = 1985;
myBook.Title = "Book Title";
myBook.AuthorName = "Author Name";

Enums

Enums are sets of named integer constants that are grouped together. The best was to demonstrate this is by example.

enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main(string[] args)
{
    Console.WriteLine(Days.Mon);        // Output: Mon
    Console.WriteLine((int)Days.Mon);   // Output: 1
}

In the example above we see that we have an enum called Days that has days of the week in it. These names represent integers 0-6 with Sun representing 0 and Sat representing 6. By default, enums start with 0 and go up by 1 for each name. You can assign a different integer value to the names as shown in the example below.

enum Days { Sun = 3, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main(string[] args)
{
    Console.WriteLine(Days.Mon);        // Output: Mon
    Console.WriteLine((int)Days.Mon);   // Output: 4
}

In the example above when we write the integer value to the console we see that the value of Mon is 4 which is due to us assigning a value of 3 to Sun. When we assign a value to an enum list item, then the following items are incremented by 1.

Arrays

Arrays are one of the ways to store a fixed size collection of elements of the same data type. The elements are sequentially ordered starting with 0 as the first element in the array.

int[] numbers = new int[] { 1, 3, 5, 7, 9 };

Console.WriteLine(numbers[0]);   // Output: 1

In this example, we are creating an array of integers named numbers. We are assigning it several numbers and then later outputting the value in that location of the array. We can create an array of any data type. For now, that is all I will cover on arrays because I have plans to publish a post covering arrays and list in much more detail.

Strings

A string is a collection of characters stored in a sequential order to form text. In the example below we are creating a string named Hello and assigning it a value of “Hello World”. I have plans to publish a post dedicated specifically to strings which will cover strings in much more detail.

string Hello = "Hello World";

Console.WriteLine(Hello);    // Output: Hello World

In this article, we discussed C# variable and more specifically what primitive and non-primitive types are. I hope that you found this article helpful and continue to follow my articles as we cover the C# programming language. As always if you have any questions or comments please comment below.

If you found this article helpful be sure to check out my C# Roadmap.