C# Basics: A Beginner’s Guide with Explanations and Examples

Rate this post

Welcome to the exciting world of C# programming! Whether you’re taking your first steps in coding or leveling up your skills, understanding the basics of C# is crucial. In this guide, we’ll explore the core concepts of C# – syntax, variables, and data types – with explanations and examples to make the learning process enjoyable.

CategorySyntax/ExampleDescription
Hello WorldConsole.WriteLine("Hello, World!");Outputs the text “Hello, World!” to the console.
Variablesint myNumber = 42;Declares an integer variable named myNumber and assigns the value 42.
Comments// This is a single-line commentSingle-line comment starts with //.
/* This is a multi-line comment */Multi-line comment starts with /* and ends with */.
Data Typesbyte myByte = 255;8-bit unsigned integer.
sbyte mySByte = -128;8-bit signed integer.
short myShort = 32767;16-bit signed integer.
ushort myUShort = 65535;16-bit unsigned integer.
int myInt = 42;32-bit signed integer.
uint myUInt = 4294967295U;32-bit unsigned integer.
long myLong = 9223372036854775807L;64-bit signed integer.
ulong myULong = 18446744073709551615UL;64-bit unsigned integer.
float myFloat = 3.14f;32-bit single-precision floating-point.
double myDouble = 3.14;64-bit double-precision floating-point.
decimal myDecimal = 123.45m;128-bit decimal type for financial calculations.
char myChar = 'A';16-bit Unicode character.
bool isTrue = true;Boolean (true/false) value.
Arithmetic Operatorsint result = 10 + 5;Addition.
int result = 10 - 5;Subtraction.
int result = 10 * 5;Multiplication.
int result = 10 / 5;Division.
int result = 10 % 3;Modulus (remainder of division).
Comparison Operatorsbool isEqual = (a == b);Equality.
bool isNotEqual = (a != b);Inequality.
bool greaterThan = (a > b);Greater than.
bool lessThan = (a < b);Less than.
bool greaterOrEqual = (a >= b);Greater than or equal to.
bool lessOrEqual = (a <= b);Less than or equal to.
Logical Operatorsbool result = (x && y);Logical AND.
`bool result = (x
bool result = !x;Logical NOT.
Conditional Statementscsharp if (condition) { /* code block */ }Executes code if the condition is true.
csharp else { /* code block */ }Executes code if the preceding condition is false.
csharp switch (variable) { case value: /* code */ break; default: /* code */ }Executes code based on the value of the variable.
Loopscsharp for (int i = 0; i < 5; i++) { /* code block */ }Executes code repeatedly for a specified number of iterations.
csharp while (condition) { /* code block */ }Executes code while a condition is true.
csharp do { /* code block */ } while (condition);Executes code at least once and then repeats while a condition is true.
Arraysint[] myArray = { 1, 2, 3, 4, 5 };Declares and initializes an integer array.
int element = myArray[2];Accesses an element in the array by index.
Functions/Methodscsharp void MyMethod() { /* code block */ }Declares a void method named MyMethod.
csharp int Add(int a, int b) { return a + b; }Declares a method that returns an integer.
int result = Add(10, 5);Calls the Add method with arguments.
Classescsharp class MyClass { /* Class members */ }Declares a class named MyClass.
Objectscsharp MyClass obj = new MyClass();Creates an instance of the MyClass class.
Propertiescsharp public int MyProperty { get; set; }Declares an auto-implemented property.
Constructorscsharp public MyClass(int value) { /* Constructor logic */ }Defines a constructor for MyClass.
Inheritancecsharp class DerivedClass : BaseClass { /* Derived class members */ }Declares a class that inherits from another class.
Interfacescsharp interface IDrawable { void Draw(); }Declares an interface with a method.
Delegatescsharp delegate int MathOperation(int x, int y);Declares a delegate for a math operation.
Eventscsharp public event EventHandler MyEvent;Declares an event named MyEvent.
Exception Handlingcsharp try { /* Code that may throw an exception */ } catch (Exception ex) { /* Handle exception */ } finally { /* Code to execute regardless of whether an exception was thrown */ }Handles exceptions using try, catch, and finally blocks.
Nullable Typesint? nullableInt = null;Represents a nullable value type.

C# Syntax

Statements and Expressions

In C# programming, statements are like sentences, and expressions are the building blocks within those sentences. A statement is a complete instruction, and an expression is a smaller part of that instruction.

Example:

// Statement example
int age = 25;

// Expression example
int newAge = age + 5;

Here, the statement declares a variable “age” and assigns it the value 25. The expression then takes that age, adds 5, and assigns the result to a new variable named “newAge.”

Variables and Identifiers

Variables act as containers to store information in a C# program. An identifier is the name given to a variable, providing a way to reference and use it in your code.

Example:

// Variable declaration
string name = "John";

In this example, we declare a variable named “name” and assign it the value “John.” The variable “name” can now be used to store and retrieve the name “John” throughout the program.

Control Flow Statements

Control flow statements direct the flow of a program’s execution, making decisions and repeating actions. Key control flow statements include if statements, loops, and switch statements.

Example:

// Control flow with if statement
int score = 80;
if (score >= 70) {
    Console.WriteLine("You passed!");
} else {
    Console.WriteLine("You need to improve.");
}

This example uses an if statement to check if the score is equal to or greater than 70. If true, it prints “You passed!”; otherwise, it suggests improvement.

Understanding C# Variables

Variable Declaration

Declaring a variable in C# involves specifying its type and giving it a name. Once declared, a variable can be used to store and manipulate data.

Example:

// Variable declaration
int numberOfApples = 10;

Here, we declare a variable named “numberOfApples” with the int type and assign it the value 10. This variable can be used to represent the quantity of apples in the program.

Scope and Lifetime of Variables

The scope of a variable defines where it can be accessed in a program, and the lifetime determines how long it exists. Variables can have local or global scope.

Example:

// Variable with local scope
void MyFunction() {
    int localVar = 5;
    Console.WriteLine(localVar);
}

The variable “localVar” is declared inside the function, making it accessible only within that function. Once the function ends, the variable’s lifetime concludes.

Constants and Readonly Variables

Constants are values that do not change throughout the program, while readonly variables can only be assigned a value once but remain accessible.

Example:

// Constant example
const double PI = 3.14;

// Readonly variable example
readonly string country = "Canada";

The constant PI will always be 3.14, and the readonly variable “country” can be set once but remains accessible throughout the program.

C# Data Types

CategoryData TypesDescriptionExample
Numeric Typesbyte8-bit unsigned integerbyte myByte = 255;
sbyte8-bit signed integersbyte mySByte = -128;
short16-bit signed integershort myShort = 32767;
ushort16-bit unsigned integerushort myUShort = 65535;
int32-bit signed integer (most commonly used)int myInt = 42;
uint32-bit unsigned integeruint myUInt = 4294967295U;
long64-bit signed integerlong myLong = 9223372036854775807L;
ulong64-bit unsigned integerulong myULong = 18446744073709551615UL;
float32-bit single-precision floating-pointfloat myFloat = 3.14f;
double64-bit double-precision floating-pointdouble myDouble = 3.14;
decimal128-bit decimal type for financial/moneydecimal myDecimal = 123.45m;
Character Typechar16-bit Unicode characterchar myChar = 'A';
Boolean TypeboolRepresents true or falsebool myBool = true;
String TypestringRepresents a sequence of charactersstring myString = "Hello, C#";
Object TypeobjectBase type for all C# typesobject myObject = new SomeClass();
Nullable TypesVarious (e.g., int?, float?)Allows representing an additional value, nullint? myNullableInt = null;
EnumerationsenumDefines a set of named valuescsharp enum Days { Sunday, Monday, Tuesday }
ArraysVarious (e.g., int[], string[])Represents a collection of elementsint[] myArray = { 1, 2, 3, 4, 5 };
StructsstructCustom value typescsharp struct Point { public int X; public int Y; }
ClassesclassCustom reference typescsharp class MyClass { /* Class members */ }
InterfacesinterfaceDefines a contract for classes to implementcsharp interface IDrawable { void Draw(); }
DelegatesdelegateDeclares and encapsulates methodscsharp delegate int MathOperation(int x, int y);

Primitive Data Types

Primitive data types are the basic building blocks that represent simple values. Common primitive data types in C# include integers, floats, chars, and booleans.

Example:

// Primitive data types
int age = 25;          // Integer
float price = 19.99f;   // Float
char grade = 'A';       // Char
bool isPassed = true;   // Boolean

In this example, we use different primitive data types to store information like age, price, grade, and pass/fail status.

Composite Data Types

Composite data types allow developers to group multiple values into a single variable. Examples include arrays, structures, and enums.

Example:

// Composite data types
int[] numbers = {1, 2, 3, 4};           // Array
struct Point { int x, y; }               // Structure
enum Days { Monday, Tuesday, Wednesday } // Enum

Here, an array holds multiple numbers, a structure groups x and y coordinates, and an enum provides names for days of the week.

Strings and Objects: C# Essentials

Strings are sequences of characters, and objects are instances of user-defined classes. Understanding these concepts helps organize and manage information effectively.

Example:

// String and Object
string greeting = "Hello, ";
string name = "John";
string welcomeMessage = greeting + name;   // Concatenating strings

class Car {
    public string model;
    public int year;
}

Car myCar = new Car();                      // Creating an object
myCar.model = "Toyota";
myCar.year = 2022;

In this example, strings are concatenated to form a welcome message, and an object representing a car is created with model and manufacturing year attributes.

Conclusion

Congratulations! You’ve now explored the foundational elements of C# programming with practical examples. Remember, practice is key. Use these explanations and examples as your starting point, and enjoy your coding journey in C#! Happy coding!

google-news
Avinash

Avinash is the Founder of Software Testing Sapiens. He is a blogger and Software Tester who has been helping people to get thier Jobs over a years Now.

Leave a Comment

whatsapp-icon
0 Shares
Copy link