C# and the Beginners Basics

Olivia
2 min readOct 11, 2021

Variables

type variableName = assignedValue

int — numbers / integers without decimals

double — integers with decimals

char — single characters ‘A’ with single quotes

string — text, with double quotes:

  • string: .Length, .ToUpper, .ToLower, .Concat
  • string interpolation: don’t need to include spaces in the variable — $"My full name is: {firstName} {lastName}"

bool/Boolean — true or false

Constants: Prevents overwriting existing values, unchangeable and read-only

Declare many: if of the same type;

int x = 1, y = 2, z = 3

Type Casting

changing one type to another.

Explicit type casting is done after the assignment operator

double myDouble = 11.05;
int myInt = (int) myDouble;

Console.WriteLine(myDouble); // Outputs 11.05
Console.WriteLine(myInt); // Outputs 11

Built-in Methods

Convert.ToString(variable name to cast);
Convert.ToDouble(variable name to cast);
Convert.ToInt32(variable name to cast);
Convert.ToBool(variable name to cast);
string birthdayMonth = "5"Console.WriteLine(Convert.ToInt32(birthdayMonth));

User Input

Console.ReadLine(); to get the users input

Console.WriteLine("What's your name?");
string yourName = Console.ReadLine();


Console.WriteLine("Hello there, " " + yourName);

Note: ReadLine(); returns a string, if using non string types, you will have to cast them

If Statement Structure

if (condition1)
{
// block of code to be executed if condition1 is True
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
else
{
// block of code to be executed if the condition1 is false and condition2 is False
}

Ternary Operator

variable = (condition) ? expressionTrue :  expressionFalse;

Switch statement

int day = 4;
switch (day)
{
case 6:
Console.WriteLine("Today is Saturday.");
break;
case 7:
Console.WriteLine("Today is Sunday.");
break;
default:
Console.WriteLine("Looking forward to the Weekend.");
break;
}
// Outputs "Looking forward to the Weekend."

Foreach

foreach (type variableName in arrayName)
{
// code block to be executed
}

Arrays

{} instead of []

Define the var type with [], store elements in{}

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Reference type

will not store the actual data but will store the reference of the variable

Provided the reference, data and data type unknown, its just storing.

object obj; // create instanceobj = 100; // called boxing
Console.WriteLine("value of obj {0}", obj)

String manipulation

string string = “Hello World World World”;

Replace

string.Replace("hello", "hi");

Insert

String.Insert(5, "C#")

AppendFormat

string.AppendFormat( "{0}", 25);

--

--

Olivia

From Law Graduate to Fullstack Developer / Professional Googler. Join me as I blog about the highs & lows of learning to code and navigating my new career path