DEV Community

Cover image for Getting started with C# - Storing and retrieving data
Jordan Taylor
Jordan Taylor

Posted on • Updated on

Getting started with C# - Storing and retrieving data

C# Variables

Variables are containers for storing data values.

In C#, there are different types of variables (defined with different keywords), for example:

int:

  • stores integers (whole numbers) without decimals, such as 123 or 123.

double:

  • stores floating-point numbers, with decimals, such as 19.99 or -19.99.

char:

  • stores single characters, such as 'a' or 'B'. Single quotes surround char values

string:

  • stores text, such as "Hello World." Double quotes surround string values

bool:

  • stores values with two states: true or false

Declaring Variables

By declaring variables we are creating a variable, you must specify the type and assign it a value:

Examples

int num = 5;
Console.Writeline(num);
Enter fullscreen mode Exit fullscreen mode
//double
double num = 3.92
Console.Writeline(num);
Enter fullscreen mode Exit fullscreen mode
string name = "Jordan";
Console.WriteLine(name);
Enter fullscreen mode Exit fullscreen mode

Modifying variables

A good thing to note is if you assign a new value to an existing variable, it will overwrite the previous value:

int myNum = 115;
myNum = 220; // myNum is now 220
Console.WriteLine(myNum);
Enter fullscreen mode Exit fullscreen mode

Constants

You can also add the const keyword to prevent others from altering the existing values; this could be helpful in certain situations.

const int numPi = 3.14
numPi = 20; // error
Enter fullscreen mode Exit fullscreen mode

The const keyword is used to tell a variable always to keep the same value.

Note: You cannot declare a constant variable without assigning the value. If you do, an error will occur: A const field requires a value to be provided.

Using the keyword var.

The var keyword has been around for a long time, and it's commonly used in code examples.

The use of the var keyword is significant in C#. There are some situations where the data type may be different than the code intended to use it.

var message = "Hello world!";

var message = 19.0m;
Enter fullscreen mode Exit fullscreen mode

Sneak Peak for the next lesson we will continue to put this all together for what we have learned so far.

int age = 25; 
int name = "Jordan";

Console.Writeline($"Hey Friends!, my name is {name}, and I am {age}!");
Enter fullscreen mode Exit fullscreen mode

If you want to dive in deep with variables take a look at the links below.

sources

Like, share and follow me ๐Ÿ”ฅ for more content:

๐Ÿ“ฝYouTube
โ˜•Buy me a coffee
๐Ÿ’–Patreon
๐ŸŒJustJordanT.com
๐Ÿฑโ€๐Ÿ’ปGitHub
๐Ÿค Twitter
๐ŸขLinkedIn

Discussion (0)