Introduction to C#

Introduction to C#

Understand the Basics of Dot Net. Duration: 21.48 mins

Introduction to C#

Click Play Button to Start

Introduction to C#

Akin to introducing JavaScript for a web development enthusiast.

About C#

  • Programming language primarily used for the Microsoft .NET framework
  • Designed by Anders Hejlsberg at Microsoft
  • Modern, object-oriented, and type-safe

Syntactical Influences

  • Draws from C and C++
  • Key differences aim for simplification and type safety
  • Automatic garbage collection reduces memory leaks
graph LR A["C and C++"] --> B["Rust"] B --> C["Simplification"] B --> D["Type Safety"] B --> E["Automatic Garbage Collection"] E --> F["Reduced Memory Leaks"] classDef default fill:#2C2C2C,stroke:#FFFFFF,color:#FFFFFF;

Similarities with JavaScript

  • Support for Object-Oriented Programming (OOP)

C#! OOP is more rigid and statically-typed compared to the dynamic, prototype-based OOP in JavaScript.

Basic Example

Let's write a 'Hello, World!' application in C#:


using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}
  

Explanation of the Code

  • using System : Imports the `System` namespace
  • namespace HelloWorld : Organizes code, similar to modules/packages in JavaScript
  • class Program : Declares a class named `Program`
  • static void Main(string[] args) : Entry point of the program
graph TD A["using System"] --> B["namespace HelloWorld"] B --> C["class Program"] C --> D["static void Main(string[] args)"] D --> E["Entry point of the program"] style A fill:#2C2C2C,stroke:#FFFFFF,color:#FFFFFF style B fill:#2C2C2C,stroke:#FFFFFF,color:#FFFFFF style C fill:#2C2C2C,stroke:#FFFFFF,color:#FFFFFF style D fill:#2C2C2C,stroke:#FFFFFF,color:#FFFFFF style E fill:#2C2C2C,stroke:#FFFFFF,color:#FFFFFF

Hello World in JavaScript


console.log('Hello, World!');
  

Comparison

  • JavaScript: Web applications
  • C#: Desktop, web, and mobile apps through .NET

Console.WriteLine in C# serves a similar purpose to console.log in JavaScript, outputting information to the console.

Understanding C# syntax

Click Play Button to Start

Understanding C# Syntax

  • Understanding C# syntax involves familiarizing with rules and structure.
  • Specific keywords, operators, punctuation, and grammar must be used correctly.
  • C# program is made up of one or more classes.
  • A class contains data and methods to work on that data.
  • Classes in C# are like objects with properties and methods in JavaScript.
graph TD A[C# Program] B[Class 1] C[Class 2] D[Class N] E[Data] F[Methods] G[Properties] H[Methods] A --> B A --> C A --> D B --> E B --> F C --> G C --> H style A fill:#2C3E50,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style B fill:#2C3E50,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style C fill:#2C3E50,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style D fill:#2C3E50,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style E fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style F fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style G fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style H fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF
Here's an example of a simple C# class definition:

using System;

namespace HelloWorldApp {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("Hello World!");
        }
    }
}
In the example above:
  • using System; : Imports modules or libraries.
  • namespace HelloWorldApp : Organizational container to avoid naming clashes.
  • class Program : Encapsulates data and methods.
  • static void Main(string[] args) : Entry point for a C# application.
  • Console.WriteLine("Hello World!"); : Prints text to console.
C# syntax rules:
  • C# is case-sensitive.
  • Each statement ends with a semicolon ( ; ).
  • Blocks of code are enclosed in curly braces ( {} ).
  • Variables are strictly typed.
  • Single-line comments start with // .
To draw an analogy with JavaScript:

class Greeter {
    constructor() {
    }

    greet() {
        console.log("Hello World!");
    }
}

const greeter = new Greeter();
greeter.greet();
  • Both examples define a class, instantiate it, and call a method to display a greeting.
  • There are differences in what is required for class declaration and execution.
  • Practicing writing simple C# classes and methods aids understanding.
graph TD classDef default fill:#2C3E50,stroke:#34495E,color:white; A[Class Definition] --> B[Instantiation] B --> C[Method Call] C --> D[Display Greeting] E[C# Syntax] --> A F[Practice] --> |Aids Understanding| G[Simple Classes] F --> |Aids Understanding| H[Methods]

Variables and data types

Click Play Button to Start

Variables and Data Types in C#

  • Variables in C# are containers for storing data values.
  • Each variable has a specific data type, determining memory size, layout, and operations.

Example of Variable Declaration


	// Declaring a variable
	int age;

	// Assigning value to the variable
	age = 25;
	

Here, `int` is a data type representing a 32-bit signed integer, and `age` is a variable of type `int`.

graph TD A["Variable Declaration"] --> B["int age;"] B --> C["age = 25;"] D["Data Type: int"] --> B E["Variable Name: age"] --> B F["Value: 25"] --> C classDef default fill:#2C2C2C,stroke:#FFFFFF,color:#FFFFFF; class A,B,C,D,E,F default;

Data Types in C#

  • Value Types
    • Integer Types: `int`, `long`, `short`, `byte` (signed and unsigned)
    • Floating Point Types: `float` (32-bit), `double` (64-bit), `decimal` (128-bit)
    • Boolean Type: `bool` (`true` or `false`)
  • Reference Types
    • Examples: `string`, `object`, custom class objects
  • Pointer Types (used in unsafe code contexts)

Value Types Example


	byte num1 = 255; // 8-bit unsigned integer
	double price = 99.95; // 64-bit double-precision floating point
	bool isCSharpFun = true; // Boolean
	

Reference Types Example


	string name = "John"; // String type
	object obj = name; // Object type, can hold any data type
	

Types of Variables

  • Local Variable : Declared inside a method or block, scope is limited to that method or block.
  • Member Variable : Declared inside a class but outside a method, accessible from any method in the class.
  • Static Variable : Declared with the `static` keyword, shared among all instances of the class.
  • Array : A data structure that stores a fixed-size sequential collection of elements of the same type.
graph TD A[Types of Variables] A --> B[Local Variable] A --> C[Member Variable] A --> D[Static Variable] A --> E[Array] B --> F["Scope: Method/Block"] C --> G["Scope: Class-wide"] D --> H["Shared among instances"] E --> I["Fixed-size collection"] style A fill:#2C3E50,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style B fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style C fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style D fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style E fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style F fill:#2980B9,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style G fill:#2980B9,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style H fill:#2980B9,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style I fill:#2980B9,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF

Comparison with JavaScript

In JavaScript, no specific data type declaration is needed when declaring variables using `let` or `const`.


	let age = 25; // No need to specify the 'int' data type explicitly
	let name = "John"; // Variables can hold any type and can be reassigned to different types
	let isLearningCSharp = true; // No data type declaration required
	

Key Distinctions

  • In JavaScript, data types are inferred at runtime (dynamically typed).
  • In C#, data types are specified at compile time (statically typed).
  • Static typing in C# helps catch type-related errors early in the development process.

Operators in C#

Click Play Button to Start

Arithmetic Operators

  • Includes: Addition ( + ), Subtraction ( - ), Multiplication ( * ), Division ( / ), and Modulus ( % )
graph LR A[Arithmetic Operators] A --> B[Addition +] A --> C[Subtraction -] A --> D[Multiplication *] A --> E[Division /] A --> F[Modulus %] style A fill:#2C3E50,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style B fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style C fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style D fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style E fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style F fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF

Example

int a = 10;
int b = 3;
int addition = a + b; // 13
int subtraction = a - b; // 7
int multiplication = a * b; // 30
int division = a / b; // 3
int modulus = a % b; // 1

Comparison Operators

  • Includes: Equality ( == ), Inequality ( != ), Greater than ( > ), Less than ( < ), Greater than or equal to ( >= ), Less than or equal to ( <= )

Example

bool isEqual = (a == b); // false
bool isNotEqual = (a != b); // true
bool isGreaterThan = (a > b); // true

Assignment Operators

  • Used to assign values to variables
  • Basic: =
  • Compound: += , -= , *= , /= , %=

Example

a += b; // equivalent to a = a + b; a becomes 13
graph TD A["a = 5"] --> B["b = 8"] B --> C["a += b"] C --> D["a = 13"] style A fill:#2C3E50,stroke:#34495E,color:white style B fill:#2C3E50,stroke:#34495E,color:white style C fill:#2C3E50,stroke:#34495E,color:white style D fill:#2C3E50,stroke:#34495E,color:white

Logical Operators

  • Combine multiple boolean expressions
  • Includes: AND ( && ), OR ( || ), NOT ( ! )

Example

bool isTrue = true;
bool isFalse = false;
bool resultAND = isTrue && isFalse; // false
bool resultOR = isTrue || isFalse; // true 
bool resultNOT = !isTrue; // false

Bitwise Operators

  • Actions on binary representations
  • Includes: AND ( & ), OR ( | ), XOR ( ^ ), NOT ( ~ ), Left Shift ( << ), Right Shift ( >> )

Example

int c = a & b; // Bitwise AND
int d = a | b; // Bitwise OR
int e = a ^ b; // Bitwise XOR

Miscellaneous Operators

  • Ternary: ?:
  • Member Access: .
  • sizeof and others

Example of Ternary Operator

int max = (a > b) ? a : b; // If a > b, max = a; otherwise, max = b

JavaScript Equivalent

  • Similar operator functionality in JavaScript

let x = 5;
let y = 2;

// Arithmetic operations
let sum = x + y; // 7

// Comparison operations
let isLess = x < y; // false

// Logical operations
let orResult = (x > 0) || (y < 0); // true

The concepts of how operators work don't change across these languages — they are essential for performing calculations and logic in both JavaScript

Decision making constructs

Click Play Button to Start

Decision-making Constructs in C#

  • Flow control based on conditions
  • Constructs: if , else , else if , switch , ? :
graph TD A[Decision-making Constructs in C#] A --> B[Flow control based on conditions] B --> C[if] B --> D[else] B --> E["else if"] B --> F[switch] B --> G["? : (Ternary)"] style A fill:#2C3E50,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style B fill:#34495E,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style C fill:#16A085,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style D fill:#16A085,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style E fill:#16A085,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style F fill:#16A085,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF style G fill:#16A085,stroke:#FFFFFF,stroke-width:2px,color:#FFFFFF

The if statement

Executes code block only if condition is true .


int number = 10;
if (number > 0)
{
    Console.WriteLine("The number is positive.");
}

The else clause

Executes code when if condition is false.


if (number > 0)
{
    Console.WriteLine("The number is positive.");
}
else
{
    Console.WriteLine("The number is non-positive.");
}

The else if construct

Handles multiple conditions; only one block executes.


if (number > 0)
{
    Console.WriteLine("The number is positive.");
}
else if (number < 0)
{
    Console.WriteLine("The número is negative.");
}
else
{
    Console.WriteLine("The número is zero.");
}

The switch statement

Tests a variable against multiple case values; runs matching code block.


switch (number)
{
    case 1:
        Console.WriteLine("The number is one.");
        break;
    case 2:
        Console.WriteLine("The number is two.");
        break;
    default:
        Console.WriteLine("The number is neither one nor two.");
        break;
}

The ?: conditional operator

Evaluates a boolean expression and returns one of two values.


string result = (number > 0) ? "positive" : "non-positive";
Console.WriteLine("The number is " + result);

Analogous Constructs in JavaScript

Similar constructs in JavaScript: if , else if , else , switch , ? :


let number = 10;
if (number > 0) {
  console.log("The number is positive.");
} else if (number < 0) {
  console.log("The number is negative.");
} else {
  console.log("The number is zero.");
}

Using switch in JavaScript


switch (number) {
  case 1:
    console.log("The number is one.");
    break;
  case 2:
    console.log("The number is two.");
    break;
  default:
    console.log("The number is neither one nor two.");
    break;
}

The ?: operator in JavaScript


let result = (number > 0) ? "positive" : "non-positive";
console.log("The number is " + result);

Understanding Constructs Through Comparison

Comparison with JavaScript eases the learning curve for C#.

graph LR A["JavaScript"] --> B["Comparison"] C["C#"] --> B B --> D["Eases Learning Curve"] D --> E["Understanding Constructs"] style A fill:#2C3E50,stroke:#FFFFFF,color:#FFFFFF style B fill:#2C3E50,stroke:#FFFFFF,color:#FFFFFF style C fill:#2C3E50,stroke:#FFFFFF,color:#FFFFFF style D fill:#2C3E50,stroke:#FFFFFF,color:#FFFFFF style E fill:#2C3E50,stroke:#FFFFFF,color:#FFFFFF

Looping constructs

Click Play Button to Start

Looping Constructs in C#

  • Looping constructs execute code repeatedly.
  • Types of loops in C#:
    • for
    • foreach
    • while
    • do-while

1. The for Loop

  • Use when number of iterations is known.
  • Parts: Initialization, Condition, Iteration.

Example:

for (int i = 0; i < 10; i++)
{
    Console.WriteLine("Iteration " + i);
}
graph TD A["for Loop"] B["Use when number of iterations is known"] C["Parts"] D["Initialization"] E["Condition"] F["Iteration"] G["Example: for (int i = 0; i < 10; i++) { Console.WriteLine('Iteration ' + i); }"] A --> B A --> C C --> D C --> E C --> F A --> G classDef default fill:#2C2C2C,stroke:#FFFFFF,color:#FFFFFF;

2. The foreach Loop

  • Iterate over items in a collection or array.

Example:

string[] names = { "Adam", "Bruce", "Charlie" };
foreach (string name in names)
{
    Console.WriteLine(name);
}

3. The while Loop

  • Runs while the condition is true.
  • Checks condition before executing.

Example:

int i = 0;
while (i < 3)
{
    Console.WriteLine("Iteration " + i);
    i++;
}

4. The do-while Loop

  • Similar to while loop.
  • Condition checked after execution.
  • Guarantees loop runs at least once.

Example:

int i = 0;
do
{
    Console.WriteLine("Iteration " + i);
    i++;
} while (i < 3);
graph TD A["Start"] B["Initialize: i = 0"] C["Execute Loop Body"] D["Print: 'Iteration ' + i"] E["Increment: i++"] F{"Is i < 3?"} G["End"] A --> B B --> C C --> D D --> E E --> F F -->|Yes| C F -->|No| G classDef default fill:#2C2C2C,stroke:#FFFFFF,color:#FFFFFF;
  • Loops can be related to JavaScript constructs.

Example in JavaScript:

for (let i = 0; i < 10; i++) {
    console.log("Iteration " + i);
}
  • Learning C# loops helps understand complex features.
  • Similarities with JavaScript can reinforce learning.

Quiz

Click Play Button to Start

Question 1/5

Who designed the C# programming language?

Question 2/5

Which of the following lines in the C# example provided is equivalent to the `console.log()` function in JavaScript?

Question 3/5

Which operator would you use in C# to combine multiple boolean expressions ensuring all conditions must be true?

Question 4/5

Which of the following statements correctly explains the behavior of the switch statement in C#?

Question 5/5

Which looping construct in C# ensures that the block of code is executed at least once, regardless of the condition?