CSharpAlltopics
CSharpAlltopics
Introduction
The "Hello World!" program is a foundational component when acquainting oneself with a new
programming language. Its primary function is to display the text "Hello World!" on the output screen,
serving as an introductory exercise to grasp essential syntax and language requirements.
"Hello World!" in C#
Code
Output
When executed, the program outputs:
Hello World!
Program Breakdown
1. Comments:
// Hello World! Program : Marks the beginning of a comment in C#. Comments are for developer
2. Namespace:
3. Class Definition:
class Hello {...} : Creates a class named Hello . In C#, class creation is mandatory as it is an
object-oriented programming language.
4. Main Method:
static void Main(string[] args) {...} : The Main() method is the starting point of execution for
Alternative Implementation
Code
namespace HelloWorld
{
class Hello {
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
In this alternative version, using System; is added at the beginning, allowing for the simplification of
System.Console.WriteLine("Hello World!"); to Console.WriteLine("Hello World!"); for convenience.
Key Takeaways
Every C# program necessitates a class definition.
This basic program serves as an introduction to C#. As the tutorial progresses, concepts will become
clearer, making it accessible even for beginners.
C# Keywords
Keywords in C# are predefined reserved words that carry specific meanings in a program and cannot be
altered. Attempting to use them as identifiers or changing their functions is prohibited. The C# language
comprises 79 keywords, all written in lowercase. Here is a comprehensive list of C# keywords:
While keywords are reserved, the prefix "@" allows them to be used as identifiers. For instance:
int @void;
Contextual Keywords
In addition to regular keywords, C# features 25 contextual keywords. These words hold specific meanings
within certain program contexts but do not have reserved status across the entire language. Contextual
keywords include:
For an in-depth understanding of each keyword, the official C# documentation can be referenced.
C# Identifiers
Identifiers serve as names for entities like variables, methods, and classes, uniquely identifying each
element in a program. However, certain rules govern their usage:
2. It must commence with a letter, underscore, or "@" symbol, followed by letters, digits, or underscores.
3. Whitespace and symbols other than letters, digits, and underscores are prohibited.
Valid:
number
calculateMarks
Invalid:
if (C# keyword)
Keywords
using
namespace
class
static
void
string
Identifiers
System
HelloWorld (namespace)
Hello (class)
Main (method)
args
Console
WriteLine
The text "Hello World!" inside the WriteLine method is a string literal.
Variables in C#
A variable in C# is a symbolic name assigned to a memory location, utilized for storing data within a
computer program. Declaration of a variable involves specifying its type and name. Here's an example:
int age;
In this case, a variable named age of type int (integer) is declared. It can later be assigned a value:
int age;
// ... ... ...
age = 24;
Variables in C# must be declared before usage, adhering to the language's static typing nature.
Implicitly typed variables can be declared using the var keyword, where the compiler determines the type
based on the assigned value:
var value = 5;
3. Whitespace and symbols other than letters, digits, and underscores are not allowed.
Boolean ( bool )
Represents true or false .
Example:
using System;
namespace DataType
{
class BooleanExample
{
public static void Main(string[] args)
{
bool isValid = true;
Console.WriteLine(isValid);
}
}
}
Signed Integral
1. sbyte
Size: 8 bits
Default value: 0
Example:
using System;
namespace DataType
{
class SByteExample
{
public static void Main(string[] args)
{
sbyte level = 23;
Console.WriteLine(level);
}
}
}
Output: 23
2. short
Size: 16 bits
Default value: 0
Example:
using System;
namespace DataType
{
class ShortExample
{
public static void Main(string[] args)
{
short value = -1109;
Console.WriteLine(value);
}
}
}
Output: -1109
3. int
Default value: 0
Example:
using System;
namespace DataType
{
class IntExample
{
public static void Main(string[] args)
{
int score = 51092;
Console.WriteLine(score);
}
}
}
Output: 51092
4. long
Size: 64 bits
Example:
using System;
namespace DataType
{
class LongExample
{
public static void Main(string[] args)
{
long range = -7091821871L;
Console.WriteLine(range);
}
}
}
Output: -7091821871
Unsigned Integral
1. byte
Size: 8 bits
Range: 0 to 255
Example:
using System;
namespace DataType
{
class ByteExample
{
public static void Main(string[] args)
{
byte age = 62;
Console.WriteLine(age);
}
}
}
Output: 62
2. ushort
Size: 16 bits
Range: 0 to 65,535
Default value: 0
Example:
using System;
namespace DataType
{
class UShortExample
{
public static void Main(string[] args)
{
ushort value = 42019;
Console.WriteLine(value);
}
}
}
Output: 42019
3. uint
Size: 32 bits
Range: 0 to 4,294,967,295
Default value: 0
Example:
Output: 1151092
4. ulong
Size: 64 bits
Range: 0 to 18,446,744,073,709,551,615
Default value: 0
Example:
using System;
namespace DataType
{
class ULongExample
{
public static void Main(string[] args)
{
ulong range = 17091821871L;
Console.WriteLine(range);
}
}
}
Output: 17091821871
Floating Point
1. float
Size: 32 bits
⁴
Range: 1.5 × 10⁻ ⁵ to 3.4 × 10³⁸
Example:
using System;
namespace DataType
Output: 43.27
2. double
Size: 64 bits
⁴
Range: 5.0 × 10⁻³² to 1.7 × 10³⁰⁸
Example:
using System;
namespace DataType
{
class DoubleExample
{
public static
Output: `-11092.53`
**Example:**
```csharp
using System;
namespace DataType
Output:
B
x
Decimal
Size: 128 bits
Example:
using System;
namespace DataType
{
class DecimalExample
{
public static void Main(string[] args)
{
decimal bankBalance = 53005.25M;
Console.WriteLine(bankBalance);
}
}
}
Output: 53005.25
C# Literals
Literals are fixed values that appear directly in the program without computation.
Boolean Literals
Integer Literals
Example:
Example:
Example:
\\\\ : Backslash
\\n : Newline
\\a : Alert
\\b : Backspace
C# Operators
double x;
x = 50.05;
using System;
namespace Operator
{
class AssignmentOperator
{
public static void Main(string[] args)
{
int firstNumber, secondNumber;
// Assigning a constant to a variable
firstNumber = 10;
Console.WriteLine("First Number = {0}", firstNumber);
Output:
First Number = 10
Second Number = 10
2. Arithmetic Operators
Arithmetic operators in C# perform operations such as addition, subtraction, multiplication, division, and
modulo (remainder). Example operations are:
int x = 5;
int y = 10;
C# Arithmetic Operators:
+ : Addition Operator
: Subtraction Operator
: Multiplication Operator
/ : Division Operator
using System;
namespace Operator
{
class ArithmeticOperator
{
public static void Main(string[] args)
{
double firstNumber = 14.40, secondNumber = 4.60, result;
int num1 = 26, num2 = 4, rem;
// Addition operator
result = firstNumber + secondNumber;
Console.WriteLine("{0} + {1} = {2}", firstNumber, secondNumber,
result);
// Subtraction operator
result = firstNumber - secondNumber;
Console.WriteLine("{0} - {1} = {2}", firstNumber, secondNumber,
result);
// Multiplication operator
result = firstNumber * secondNumber;
Console.WriteLine("{0} * {1} = {2}", firstNumber, secondNumber,
result);
// Division operator
result = firstNumber / secondNumber;
Console.WriteLine("{0} / {1} = {2}", firstNumber, secondNumber,
result);
// Modulo operator
rem = num1 % num2;
Console.WriteLine("{0} % {1} = {2}", num1, num2, rem);
}
Output:
14.4 + 4.6 = 19
14.4 - 4.6 = 9.8
14.4 * 4.6 = 66.24
14.4 / 4.6 = 3.1304347826087
26 % 4 = 2
3. Relational Operators
Relational operators check the relationship between two operands and result in either true or false.
Examples include:
bool result;
int firstNumber = 10, secondNumber = 20;
C# Relational Operators:
== : Equal to
!= : Not equal to
using System;
namespace Operator
{
class RelationalOperator
{
public static void Main(string[] args)
{
bool result;
int firstNumber = 10, secondNumber = 20;
Output:
10 == 20 returns False
10 > 20 returns False
10 < 20 returns True
10 >= 20 returns False
10 <= 20 returns True
10 != 20 returns True
4. Logical Operators
Logical operators ( && for AND, || for OR) perform logical operations on boolean expressions, resulting in
boolean values. Example usage:
bool result;
int firstNumber = 10, secondNumber = 20;
// OR operator
result = (firstNumber == secondNumber) || (firstNumber > 5);
C# Logical Operators:
|| : Logical OR
using System;
namespace Operator
{
class LogicalOperator
{
public static void Main(string[] args)
{
bool result;
int firstNumber = 10, secondNumber = 20;
// OR operator
result = (firstNumber == secondNumber) || (firstNumber > 5);
Console.WriteLine(result);
// AND operator
result = (firstNumber == secondNumber) && (firstNumber > 5);
Console.WriteLine(result);
}
}
}
Output:
True
False
5. Unary Operators
Unary operators ( + , - , ++ , -- , ! ) operate on a single operand. Examples include:
C# Unary Operators:
+ : Unary Plus
: Unary Minus
++`: Increment
- : Decrement
using System;
namespace Operator
{
class UnaryOperator
{
public static void Main(string[] args)
{
int number = 10, result;
bool flag = true;
result = +number;
Console.WriteLine("+number = " + result);
result = -number;
Console.WriteLine("-number = " + result);
result = ++number;
Console.WriteLine("++number = " + result);
result = --number;
Console.WriteLine("--number = " + result);
Output:
+number = 10
-number = -10
++number = 11
For further details on increment and decrement operators, refer to Example 6 in the provided code.
6. Ternary Operator
The ternary operator ( ? : ) in C# acts as a shorthand for an if-then-else statement. It is used in scenarios
where a decision needs to be made based on a condition. Example:
using System;
namespace Operator
{
class TernaryOperator
{
public static void Main(string[] args)
{
int number = 10;
string result = (number % 2 == 0) ? "Even Number" : "Odd Numbe
r";
Console.WriteLine("{0} is {1}", number, result);
}
}
}
Output:
10 is Even Number
~ : Bitwise Complement
| : Bitwise OR
^ : Bitwise Exclusive OR
using System;
namespace Operator
{
class BitOperator
{
public static void Main(string[] args)
{
int firstNumber = 10;
int secondNumber = 20;
int result;
result = ~firstNumber;
Console.WriteLine("~{0} = {1}", firstNumber, result);
Output:
~10 = -11
10 & 20 = 0
10 | 20 = 30
10 ^ 20 = 30
10 << 2 = 40
10 >> 2 = 2
+= : Addition Assignment
= : Subtraction Assignment
= : Multiplication Assignment
/= : Division Assignment
%= : Modulo Assignment
|= : Bitwise OR Assignment
using System;
namespace Operator
{
class BitOperator
{
public static void Main(string[] args)
{
int number = 10;
number += 5;
Console.WriteLine(number);
number -= 3;
Console.WriteLine(number);
number *= 2;
Console.WriteLine(number);
number /= 3;
Console.WriteLine(number);
number %= 3;
Console.WriteLine(number);
number |= 14;
Console.WriteLine(number);
number ^= 12;
Console.WriteLine(number);
number <<= 2;
Console.WriteLine(number);
number >>= 3;
Console.WriteLine(number);
}
Output:
15
12
24
8
2
2
14
2
8
1
The provided examples cover a comprehensive overview of various operators in C#, aiding in arithmetic
using System;
namespace Operator
{
class OperatorPrecedence
{
public static void Main(string[] args)
{
int result1;
int a = 5, b = 6, c = 4;
result1 = --a * b - ++c;
Console.WriteLine(result1);
bool result2;
result2 = b >= c + a;
Console.WriteLine(result2);
}
}
}
Output:
Explanation:
1. For the expression result1 = --a * b - ++c; , the operators - and ++ have higher precedence than
and . The expression is equivalent to result1 = ((--a) * b) - (++c) .
2. For the expression result2 = b >= c + a; , the precedence of + is higher than >= . Thus, c + a is
calculated first, resulting in 9. The comparison b >= 9 is evaluated, yielding False .
C# Operator Precedence
Category Operators
-------------------------------------------
Postfix Increment and Decrement ++, --
Prefix Increment, Decrement, Unary ++, --, +, -, !, ~
Multiplicative *, /, %
Additive +, -
Shift <<, >>
Relational <, <=, >, >=
Equality ==, !=
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
Logical AND &&
Logical OR ||
Ternary ? :
Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
Associativity of Operators in C#
When operators of the same precedence appear in an expression, the associativity of the operators
determines the order of evaluation. In C#, most operators have left-to-right associativity.
using System;
namespace Operator
{
a = b = c;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
}
}
}
Output:
10
a = 3, b = 3, c = 3
Explanation:
1. For the expression result = a * b / c; , the operators and / have the same precedence, but their
associativity is left-to-right. Therefore, a * b is evaluated first, resulting in 30, and then 30 / c is
calculated, yielding result as 10.
2. For the expression a = b = c; , the assignment operator = has right-to-left associativity. The value of
c (3) is assigned to b , and then the value of b is assigned to a . After this statement, the values of
a , b , and c are all 3.
~ Bitwise Complement
| Bitwise OR
Bitwise OR Operator ( | )
using System;
namespace Operator
{
class BitWiseOR
{
public static void Main(string[] args)
{
int firstNumber = 14, secondNumber = 11, result;
result = firstNumber | secondNumber;
Console.WriteLine("{0} | {1} = {2}", firstNumber, secondNumber,
result);
}
}
}
Output:
14 | 11 = 15
using System;
namespace Operator
{
class BitWiseAND
{
public static void Main(string[] args)
{
int firstNumber = 14, secondNumber = 11, result;
result = firstNumber & secondNumber;
Console.WriteLine("{0} & {1} = {2}", firstNumber, secondNumber,
result);
}
}
}
Output:
using System;
namespace Operator
{
class BitWiseXOR
{
public static void Main(string[] args)
{
int firstNumber = 14, secondNumber = 11, result;
result = firstNumber ^ secondNumber;
Console.WriteLine("{0} ^ {1} = {2}", firstNumber, secondNumber,
result);
}
}
}
Output:
14 ^ 11 = 5
using System;
namespace Operator
{
class BitWiseComplement
{
public static void Main(string[] args)
{
int number = 26, result;
result = ~number;
Console.WriteLine("~{0} = {1}", number, result);
}
Output:
~26 = -27
using System;
namespace Operator
{
class LeftShift
{
public static void Main(string[] args)
{
int number = 42;
Output:
42<<1 = 84
42<<2 = 168
42<<4 = 672
using System;
namespace Operator
{
Output:
42>>1 = 21
42>>2 = 10
42>>4 = 2
1. System.Console.WriteLine()
2. System.Console.Write()
In these methods, System is the namespace, Console is a class within the System namespace, and
WriteLine and Write are methods of the Console class.
using System;
namespace Sample
{
class Test
{
public static void Main(string[] args)
{
Console.WriteLine("C# is cool");
}
}
}
Output:
using System;
namespace Sample
{
class Test
{
public static void Main(string[] args)
{
Console.WriteLine("Prints on ");
Console.WriteLine("New line");
Console.Write("Prints on ");
Console.Write("Same line");
}
}
}
Output:
Prints on
New line
Prints on Same line
using System;
namespace Sample
{
class Test
{
public static void Main(string[] args)
{
int value = 10;
Output:
10
50.05
using System;
namespace Sample
{
class Test
{
public static void Main(string[] args)
{
int val = 55;
Console.WriteLine("Hello " + "World");
Console.WriteLine("Value = " + val);
}
}
}
Output:
Hello World
Value = 55
using System;
namespace Sample
Output:
5 + 10 = 15
C# Input
In C#, user input is commonly obtained using the ReadLine() method of the Console class. Additionally,
Read() and ReadKey() methods are available for different input scenarios.
using System;
namespace Sample
{
class Test
{
public static void Main(string[] args)
{
string testString;
Console.Write("Enter a string - ");
testString = Console.ReadLine();
Console.WriteLine("You entered '{0}'", testString);
}
}
}
Output:
Read() : Reads the next character from the standard input stream and returns the ASCII value of the
character.
ReadKey() : Obtains the next key pressed by the user and is typically used to wait for a key press.
using System;
namespace Sample
{
class Test
{
public static void Main(string[] args)
{
int userInput;
Output:
using System;
namespace UserInput
{
class MyClass
{
Output:
In this example, ToInt32() and ToDouble() methods of the Convert class are used to convert the string
input to integer and double types, respectively.
C# Expressions
Expressions in C# are combinations of operands (variables, literals, method calls) and operators that
evaluate to a single value. An expression must have at least one operand, but it may not necessarily
include an operator.
Example 1:
double temperature;
temperature = 42.05;
int a, b, c, sum;
sum = a + b + c;
Here, (age >= 18 && age < 58) is an expression that returns a boolean value. "Eligible to work" is also an
expression.
C# Statements
A statement is a basic unit of program execution, and a program consists of multiple statements. There are
different types of statements in C#, and we'll focus on two main types in this tutorial: declaration
statements and expression statements.
Declaration Statement
Declaration statements are used to declare and initialize variables.
char ch;
int maxValue = 55;
Both char ch; and int maxValue = 55; are declaration statements.
Expression Statement
An expression followed by a semicolon is called an expression statement.
/* Assignment */
area = 3.14 * radius * radius;
/* Method call is an expression */
System.Console.WriteLine("Hello");
Here, 3.14 * radius * radius is an expression, and area = 3.14 * radius * radius; is an expression
statement. Similarly, System.Console.WriteLine("Hello"); is both an expression and a statement.
Besides declaration and expression statements, there are:
C# Blocks
A block is a combination of zero or more statements enclosed inside curly brackets { } .
namespace Blocks
{
class BlockExample
{
public static void Main(string[] args)
{
double temperature = 42.05;
if (temperature > 32)
{ // Start of block
Console.WriteLine("Current temperature = {0}", temperatur
e);
Console.WriteLine("It's hot");
} // End of block
}
}
}
Output:
using System;
namespace Blocks
{
class BlockExample
{
public static void Main(string[] args)
{
double temperature = 42.05;
if (temperature > 32)
{ // Start of block
// No statements
} // End of block
}
}
}
Here, the curly braces { } after if(temperature > 32) contain only comments and no statements.
namespace HelloWorld
{
class Program
{
public static void Main(string[] args) // Execution Starts from Ma
in method
{
// Prints Hello World
Console.WriteLine("Hello World!");
}
}
}
/*
This is a Hello World Program in C#.
This program prints Hello World.
*/
using System;
namespace HelloWorld
{
class Program
{
/* This is a Hello World Program in C#. This program prints Hello World. */
/// <summary>
/// This is a hello world program.
/// </summary>
using System;
namespace HelloWorld
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
The XML documentation comment used in the above program is /// <summary> This is a hello world
program. </summary> .
Comments should be used judiciously:
Flow Control
C# if Statement
The if statement in C# executes a block of code if the given condition is true. The syntax is as follows:
if (boolean-expression)
{
// statements executed if boolean-expression is true
}
Example 1: C# if Statement
using System;
namespace Conditional
{
class IfStatement
{
public static void Main(string[] args)
{
int number = 2;
if (number < 5)
{
Console.WriteLine("{0} is less than 5", number);
}
Output:
2 is less than 5
This statement is always executed.
Explanation: The code inside the if block is executed because the value of number is less than 5.
C# if...else Statement
using System;
namespace Conditional
{
class IfElseStatement
{
public static void Main(string[] args)
{
int number = 12;
if (number < 5)
{
Console.WriteLine("{0} is less than 5", number);
}
else
{
Console.WriteLine("{0} is greater than or equal to 5", numb
er);
}
Output:
Explanation: The code inside the else block is executed as the value of number is greater than or equal to
5.
C# if...else if Statement
The if...else if statement allows testing multiple conditions in sequence. The block of code associated
with the first true condition is executed.
using System;
namespace Conditional
{
if (number < 5)
{
Console.WriteLine("{0} is less than 5", number);
}
else if (number > 5)
{
Console.WriteLine("{0} is greater than 5", number);
}
else
{
Console.WriteLine("{0} is equal to 5");
}
}
}
}
Output:
12 is greater than 5
Explanation: The code inside the else if block is executed as the first condition is false, and the second
condition is true.
using System;
namespace Conditional
{
class Nested
{
public static void Main(string[] args)
{
int first = 7, second = -23, third = 13;
if (first > second)
{
if (first > third)
{
Output:
13 is the largest
Explanation: The program finds the largest among three numbers using nested if...else statements. In this
case, 13 is the largest.
C# switch Statement
The switch statement in C# serves as an alternative to the if...else if statement, providing cleaner and
more readable code. This statement is particularly advantageous when dealing with multiple conditions.
The switch statement evaluates the expression or variable and compares its value with the values
listed in each case.
When a matching value is found, the statements inside that case are executed.
If none of the cases match, the statements inside the default block are executed.
Note: The break statement is crucial to terminate the execution of the switch statement once a match is
found. Without break , it would execute all statements until the end of the switch block.
using System;
namespace Conditional
{
class SwitchCase
{
public static void Main(string[] args)
{
char ch;
Console.WriteLine("Enter an alphabet");
ch = Convert.ToChar(Console.ReadLine());
switch (Char.ToLower(ch))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
Console.WriteLine("Vowel");
break;
default:
Console.WriteLine("Not a vowel");
break;
}
}
}
}
Output:
Enter an alphabet
X
Not a vowel
using System;
namespace Conditional
{
class SwitchCase
{
public static void Main(string[] args)
{
char op;
double first, second, result;
switch (op)
{
case '+':
result = first + second;
Console.WriteLine("{0} + {1} = {2}", first, second, res
ult);
break;
case '-':
result = first - second;
Console.WriteLine("{0} - {1} = {2}", first, second, res
ult);
break;
case '*':
result = first * second;
Console.WriteLine("{0} * {1} = {2}", first, second, res
ult);
break;
case '/':
result = first / second;
Console.WriteLine("{0} / {1} = {2}", first, second, res
ult);
break;
default:
Console.WriteLine("Invalid Operator");
break;
Output:
Explanation: This program performs basic arithmetic operations based on user input using the switch
statement.
In summary, the switch statement in C# is a valuable tool for simplifying decision-making structures,
especially when dealing with multiple conditions. It enhances code readability and can be a powerful asset
in scenarios where it is applicable.
C# Ternary Operator
The ternary operator in C# serves as a concise alternative to the traditional if...else statement. Its syntax
is as follows:
using System;
namespace Conditional
{
class Ternary
{
public static void Main(string[] args)
{
int number = 2;
bool isEven;
Output:
True
Explanation: In this example, the program checks if the variable number is even using the ternary operator.
Since 2 is even, the expression (number % 2 == 0) evaluates to true, and the result true is assigned to the
variable isEven .
It's worth noting that the ternary operator can be used to return various types, including numbers, strings,
and characters.
Simplicity: Use the ternary operator to replace simple if...else statements and improve code
simplicity.
Readability: Avoid overusing the ternary operator, as it may decrease code readability, making it
challenging to understand the logic.
Complexity: For complex conditions and multiple branches, sticking with if...else statements may
enhance code clarity.
using System;
namespace Conditional
{
class Ternary
{
public static void Main(string[] args)
{
int a = 5, b = 10;
string result;
Output:
b is greater than a
C# For Loop
In programming, the need to execute a block of statements for a specified number of times is common.
Loops are employed to repeatedly execute a certain block of statements until a specified condition is met.
In C#, the for loop is utilized for this purpose.
C# for Loop
The for keyword is used to create a for loop in C#. The syntax is as follows:
3. If the condition is true, the statements inside the loop are executed. Then, the iterator statement is
executed, typically changing the initialized variable's value. The loop continues until the condition is
false.
using System;
namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
}
}
Output:
In this program, i is initialized to 1, and the loop continues until i is no longer less than or equal to 5.
using System;
namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
int n = 5, sum = 0;
Output:
Here, the loop is used to compute the sum of the first n natural numbers.
using System;
namespace Loop
{
Output:
i = 0 and j = 0
i = 1 and j = 1
i = 2 and j = 2
In this program, multiple variables are declared and initialized in the initialization statement, and both i
using System;
namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
int i = 1;
for (; i <= 5;)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
i++;
}
}
}
}
Output:
In this example, the initialization and iterator statements are omitted, and the loop still functions as
expected.
using System;
namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
for (int i = 1; i > 0; i++)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
}
}
}
}
In this program, an infinite for loop is created where the condition is always true.
It's important to note that the initialization, condition, and iterator statements are optional in a for loop,
and when omitted, the loop serves as a while loop. However, caution should be exercised to avoid infinite
loops by ensuring that the condition eventually becomes false.
C# While Loop
The while keyword is used to create a while loop in C#. The syntax is as follows:
while (test-expression)
{
// body of while loop
}
1. If the test-expression is true, the statements inside the while loop are executed.
using System;
namespace Loop
{
class WhileLoop
{
public static void Main(string[] args)
{
int i = 1;
while (i <= 5)
{
Console.WriteLine("C# While Loop: Iteration {0}", i);
i++;
}
}
}
}
Output:
In this program, the loop executes until the value of i becomes 6. The test-expression i <= 5 ensures
the loop runs as long as i is less than or equal to 5.
using System;
namespace Loop
{
class WhileLoop
{
public static void Main(string[] args)
{
int i = 1, sum = 0;
while (i <= 5)
{
Output:
Sum = 15
This program computes the sum of the first 5 natural numbers using a while loop.
C# Do...While Loop
The and while keywords are used to create a do...while loop. In contrast to the
do while loop, the
do...while loop executes the body first and then checks the test-expression.
do
{
// body of do while loop
} while (test-expression);
using System;
namespace Loop
{
class DoWhileLoop
{
public static void Main(string[] args)
{
int i = 1, n = 5, product;
do
{
product = n * i;
Output:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
This program prints the multiplication table of the number 5 using a do...while loop. The loop runs at least
once, irrespective of the test-expression.
while (true)
{
// body of while loop
}
do
{
// body of while loop
} while (true);
It's crucial to exercise caution with infinite loops to prevent unintended consequences and ensure the loop
is terminated appropriately in your program.
using System;
namespace Loop
{
class NestedForLoop
{
public static void Main(string[] args)
{
int outerLoop = 0, innerLoop = 0;
for (int i = 1; i <= 5; i++)
{
outerLoop++;
for (int j = 1; j <= 5; j++)
{
innerLoop++;
}
}
Console.WriteLine("Outer Loop runs {0} times", outerLoop);
Console.WriteLine("Inner Loop runs {0} times", innerLoop);
}
}
}
Output:
using System;
namespace Loop
{
class NestedForLoop
{
public static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(j + " ");
}
Console.WriteLine();
}
}
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
while (condition-1)
{
// body of outer while loop
while (condition-2)
{
// body of inner while loop
}
// body of outer while loop
}
using System;
namespace Loop
{
class NestedWhileLoop
{
public static void Main(string[] args)
{
int i = 0;
while (i < 2)
{
int j = 0;
while (j < 2)
{
Console.Write("({0},{1}) ", i, j);
j++;
}
i++;
Console.WriteLine();
}
}
}
}
Output:
(0,0) (0,1)
(1,0) (1,1)
This program demonstrates the usage of nested while loops to print pairs of numbers.
do
{
// body of outer do-while loop
do
{
// body of inner do-while loop
} while (condition-2);
// body of outer do-while loop
} while (condition-1);
namespace Loop
{
class NestedWhileLoop
{
public static void Main(string[] args)
{
int i = 0;
do
{
int j = 0;
do
{
Console.Write("({0},{1}) ", i, j);
j++;
} while (j < 2);
i++;
Console.WriteLine();
Output:
(0,0) (0,1)
(1,0) (1,1)
This program showcases the usage of nested do-while loops to print pairs of numbers.
using System;
namespace Loop
{
class NestedLoop
{
public static void Main(string[] args)
{
int i = 1;
Console.WriteLine();
i++;
}
}
}
}
Output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
In this program, a for loop is nested within a while loop, demonstrating the flexibility of nesting different
types of loops.
C# Break Statement
In C#, the break statement is utilized to terminate a loop prematurely. While loops iterate over a block of
code until the test expression is false, the break statement allows us to exit the loop immediately without
evaluating the test expression.
namespace CSharpBreak
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 4; ++i)
{
// Terminates the loop when i is equal to 3
if (i == 3)
{
break;
}
Console.ReadLine();
}
}
}
Output:
1
2
In the above program, the for loop runs four times, but when i is equal to 3, the break statement is
encountered, causing the loop to terminate immediately. Consequently, only the values 1 and 2 are
printed.
namespace WhileBreak
{
class Program
{
static void Main(string[] args)
{
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++;
}
Console.ReadLine();
}
}
}
Output:
In this example, a while loop is used to run from i = 1 to i = 5 . However, the loop terminates when i is
equal to 4 due to the break statement.
using System;
namespace NestedBreak
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
for (int i = 1; i <= 3; i++) // Outer loop
{
for (int j = 1; j <= 3; j++) // Inner loop
{
// Terminates the inner loop when i is equal to 2
if (i == 2)
{
break;
}
Console.ReadLine();
}
}
}
Output:
i = 1 j = 1
i = 1 j = 2
In this example, the break statement is used inside the inner loop. Consequently, the inner loop terminates
when i is equal to 2, while the outer loop continues.
using System;
namespace ForEachBreak
{
class Program
{
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
Console.WriteLine(number);
}
}
}
}
Output:
1
2
In this example, the foreach loop prints each element of the array, but it terminates when the element is
equal to 3 due to the break statement.
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
char ch = 'e';
switch (ch)
{
case 'a':
Console.WriteLine("Vowel");
break;
case 'e':
Console.WriteLine("Vowel");
break;
case 'i':
Console.WriteLine("Vowel");
break;
case 'o':
Console.WriteLine("Vowel");
break;
case 'u':
Console.WriteLine("Vowel");
break;
default:
Console.WriteLine("Not a vowel");
break;
}
}
}
}
Output:
Vowel
Here, the break statement is used inside each case to terminate the switch statement when a matching
case is found.
namespace ContinueLoop
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 5; ++i)
{
// Skips the iteration when i is equal to 3
if (i == 3)
{
continue;
}
Console.WriteLine(i);
}
}
}
}
Output:
1
2
4
5
In this example, the for loop is utilized to print numbers from i = 1 to 5 . However, the number 3 is not
printed because the continue statement is executed when i is equal to 3. This skips the current iteration
of the loop.
using System;
namespace ContinueWhile
{
class Program
Console.WriteLine(i);
}
}
}
}
Output:
1
2
4
5
The continue statement is used inside the while loop in a similar manner. When the value of i is 3, the
continue statement is executed, skipping the print statement for that iteration.
using System;
namespace ContinueNested
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
Output:
i = 1 j = 1
i = 1 j = 3
i = 2 j = 1
i = 2 j = 3
i = 3 j = 1
i = 3 j = 3
In this example, the continue statement is used inside the inner for loop. It skips the iteration when j is
equal to 2, resulting in the omission of the value 2 in the output.
using System;
namespace ContinueForeach
{
class Program
{
static void Main(string[] args)
{
int[] num = { 1, 2, 3, 4, 5 };
Console.WriteLine(number);
}
}
}
}
Output:
1
2
4
5
Here, the foreach loop prints each element of the array, but it skips the value 3 when encountered, due to
the continue statement.
C# Arrays
An array in C# is a collection of elements of the same data type. Instead of creating separate variables, an
array allows you to store and manage multiple values more efficiently. Let's explore the essential concepts
related to arrays in C#.
1. C# Array Declaration
In C#, you declare an array using the following syntax:
dataType[] arrayName;
dataType : Represents the data type of the elements in the array (e.g., int , string , char ).
For example:
int[] age;
To specify the number of elements an array can hold, you need to allocate memory using the new
keyword:
In this case, C# automatically determines the size of the array based on the number of elements provided.
You can also use index numbers to initialize elements individually:
// Initializing array
age[0] = 12;
age[1] = 4;
age[2] = 5;
// ...
Note:
Array indices start at 0, and the last element's index is one less than the array size.
You can use these indices to access specific elements in the array.
Example: C# Array
using System;
namespace AccessArray
{
class Program
{
static void Main(string[] args)
{
// Create an array
int[] numbers = {1, 2, 3};
Console.ReadLine();
}
}
}
Output:
In this example, we use array indices to access elements of the array numbers .
// Create an array
int[] numbers = {1, 2, 3};
Output:
using System;
namespace AccessArrayFor
Console.ReadLine();
}
}
}
Output:
Element in index 0: 1
Element in index 1: 2
Element in index 2: 3
using System;
namespace AccessArrayForeach
{
class Program
{
static void Main(string[] args)
{
int[] numbers = {1, 2, 3};
Console.ReadLine();
}
}
}
Array Elements:
1
2
3
using System;
using System.Linq;
namespace ArrayMinMax
{
class Program
{
static void Main(string[] args)
{
int[] numbers = {51, 1, 3, 4, 98};
Console.ReadLine();
}
}
}
Output:
Smallest Element: 1
Largest Element: 98
using System;
using System.Linq;
namespace ArrayFunction
{
class Program
Console.ReadLine();
}
}
}
Output:
Average: 59.2
Average using Average(): 59.2
Remember to include the System.Linq namespace for methods like Min() , Max() , Sum() , Count() , and
Average() .
C# Multidimensional Array
Before delving into multidimensional arrays in C#, it's crucial to understand single-dimensional arrays. A
multidimensional array, in C#, comprises elements that are themselves arrays. For example:
int[,] x = { { 1, 2, 3 }, { 3, 4, 5 } };
Here, x is a multidimensional array with two elements: {1, 2, 3} and {3, 4, 5}. Each element of the array is
also an array with three elements.
int[,] x = { { 1, 2, 3 }, { 3, 4, 5 } };
In this case, x is a 2D array with two elements: {1, 2, 3} and {3, 4, 5}. The number of rows and columns is
determined by the initialization.
You can also specify the number of rows and columns during initialization:
// A 2D array
int[,] x = { { 1, 2, 3 }, { 3, 4, 5 } };
Example: C# 2D Array
using System;
namespace MultiDArray
{
class Program
{
static void Main(string[] args)
{
// Initializing a 2D array
int[,] numbers = {{2, 3}, {4, 5}};
Output:
In this example, the program creates a 2D array named numbers with rows {2, 3} and {4, 5}. The index
numbers are used to access elements of the 2D array.
using System;
namespace MultiDArray
{
class Program
{
static void Main(string[] args)
{
int[,] numbers = {{2, 3}, {4, 5}};
// Old element
Console.WriteLine("Old element at index [0, 0] : " + numbers[0,
0]);
// New element
Console.WriteLine("New element at index [0, 0] : " + numbers[0,
0]);
}
}
}
Output:
namespace MultiDArray
{
class Program
{
static void Main(string[] args)
{
int[,] numbers = { { 2, 3, 9 }, { 4, 5, 9 } };
Output:
Row 0: 2 3 9
Row 1: 4 5 9
This example uses a nested for loop to iterate through the elements of a 2D array. The GetLength(0)
method gives the number of rows, and GetLength(1) gives the number of elements in a row.
Note: You can also create a 3D array, which is essentially an array with multiple two-dimensional arrays as
its elements. For example:
int[,,] numbers = { { { 1, 3, 5 }, { 2, 4, 6 } }, { { 2, 4, 9 }, { 5, 7, 11
} } };
C# Jagged Array
C# Arrays
C# Multidimensional Arrays
For example:
Here, int is the data type, [][] represents a jagged array, jaggedArray is the array's name, and [2][]
int[][] jaggedArray = {
new int[] {10, 20, 30},
new int[] {11, 22},
new int[] {88, 99}
};
namespace JaggedArray
{
class Program
{
static void Main(string[] args)
{
// Create a jagged array
int[][] jaggedArray = {
new int[] {1, 3, 5},
new int[] {2, 4},
};
Console.ReadLine();
Output:
jaggedArray[1][0]: 2
jaggedArray[1][1]: 4
jaggedArray[0][2]: 5
Output:
Element 0: 1 3 5
Element 1: 2 2
In this example, a nested for loop is used to iterate through the jagged array. The outer loop accesses
the elements (arrays) of the jagged array, and the inner loop accesses the elements of the individual
arrays inside the jagged array.
Here, each element of the jagged array is a multidimensional array. An example is provided:
using System;
namespace JaggedArray
{
class Program
{
static void Main(string[] args)
{
// Declare and initialize jagged array with 2D array
int[][,] jaggedArray = new int[3][,] {
new int[,] { {1, 8}, {6, 7} },
new int[,] { {0, 3}, {5, 6}, {9, 10} },
new int[,] { {11, 23}, {100, 88}, {0, 10} }
};
Console.WriteLine(jaggedArray[0][0, 1]);
Console.WriteLine(jaggedArray[1][2, 1]);
Console.WriteLine(jaggedArray[2][1, 0]);
Console.ReadLine();
}
}
}
Output:
In this example, the code jaggedArray[0][0, 1] refers to the second element of the first
array inside the 2D array.
C# foreach loop
C# provides a more readable and user-friendly alternative to the traditional for loop - the foreach loop. It
is particularly beneficial when working with arrays and collections, simplifying the iteration process. Before
delving into the details of the foreach loop, ensure familiarity with the following:
C# for loop
C# arrays
C# collections
Here, iterable-item can be an array or a class of collection. The in keyword, used with the foreach loop,
iterates over the iterable-item . It selects an item from the iterable-item on each iteration and stores it in
the variable element .
using System;
namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
char[] myArray = {'H','e','l','l','o'};
using System;
namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
char[] myArray = {'H','e','l','l','o'};
foreach(char ch in myArray)
{
Console.WriteLine(ch);
}
}
}
}
In the above programs, both using for and foreach loops achieve the same task of printing each
character of the array. However, the foreach loop provides a more readable and concise syntax.
using System;
namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
char[] gender = {'m','f','m','m','m','f','f','m','m','f'};
int male = 0, female = 0;
foreach (char g in gender)
{
if (g == 'm')
using System;
using System.Collections.Generic;
namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
var numbers = new List<int>() { 5, -8, 3, 14, 9, 17, 0, 4 };
int sum = 0;
foreach (int number in numbers) {
sum += number;
}
Console.WriteLine("Sum = {0}", sum);
Console.ReadLine();
}
}
}
In this program, the foreach loop is used to traverse through a collection. Traversing a collection is similar
to traversing through an array, where each element of the collection is processed in order.
When using the foreach loop, the resulting code is often more readable and easier to understand
compared to the traditional for loop, especially when working with arrays and collections.
C# Class
class ClassName {
// Fields
dataType fieldName;
// Methods
returnType MethodName() {
// Method body
}
}
For example:
class Dog {
// Field
string breed;
// Method
public void Bark() {
// Method body
}
}
In this illustration, Dog is the class with a field breed and a method Bark .
C# Objects
Objects are instances of classes. If a class is likened to a blueprint, objects are the actual houses built
from that blueprint. To create an object in C#, the new keyword is employed:
This demonstrates accessing the Breed field and invoking the Bark method of the Dog class.
Both sheeran and taylor are objects of the Employee class, each with its own Department field.
C# Method
A method in C# is a block of code designed to perform a specific task. In OOP, it aids in breaking down
complex problems into manageable units. Methods are crucial for creating modular and reusable code.
Declaring a Method in C#
The syntax for declaring a method in C# is as follows:
returnType MethodName() {
// method body
}
returnType: Specifies the type of value the method returns. If no value is returned, void is used.
method body: The block of code containing statements to perform specific tasks.
For example:
Here, Display is the method name, and the return type is void .
Calling a Method in C#
After declaring a method, it needs to be called to execute the code within it. Calling a method is done
using the following syntax:
MethodName();
For example:
Display();
Example: C# Method
using System;
namespace Method {
class Program {
// method declaration
public void Display() {
Console.WriteLine("Hello World");
}
// call method
p1.Display();
Console.ReadLine();
}
}
}
Output:
Hello World
using System;
namespace Method {
class Program {
// method declaration
static int AddNumbers() {
int sum = 5 + 14;
return sum;
}
// call method
int sum = AddNumbers();
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
Output:
19
C# Methods Parameters
Methods in C# can accept parameters, allowing them to receive values during the call. Parameters are
specified within the method parentheses.
Example:
using System;
namespace Method {
// call method
int sum = p1.AddNumber(100, 100);
Console.ReadLine();
}
}
}
Output:
Sum: 200
Built-in Methods
C# provides built-in methods that can be used directly in programs. These include methods like Sqrt()
using System;
namespace Method {
class Program {
static void Main(string[] args) {
// Built-in method
double a = Math.Sqrt(9);
Console.WriteLine("Square root of 9: " + a);
}
}
}
Output:
In this example, the Sqrt() method is used from the Math class.
Method Overloading in C#
C# supports method overloading, allowing the creation of multiple methods with the same name but
different parameters.
Example:
using System;
namespace MethodOverload {
class Program {
Output:
Arguments: 100
Arguments: 100 and 200
In this example, the Display method is overloaded with different numbers of parameters.
C# Access Modifiers
Access modifiers in C# dictate the accessibility of types (e.g., classes, interfaces) and type members (e.g.,
fields, methods). They play a crucial role in controlling the visibility and interaction of different components
within a program.
1. Public:
When a type or type member is declared as public, it can be accessed from anywhere.
Example:
class Student {
public string name = "Sheeran";
In this example, both the name field and the Print method are public and can be accessed from the
Program class.
2. Private:
When a type member is declared as private, it can only be accessed within the same class or
struct.
Example:
class Student {
private string name = "Sheeran";
In this case, attempting to access the name field or the Print method from the Program class would
result in an error.
3. Protected:
When a type member is declared as protected, it can only be accessed from the same class and
its derived classes.
Example:
class Student {
protected string name = "Sheeran";
}
In this example, attempting to access the name field directly from the Program class results in an error.
However, it can be accessed within a derived class, as shown.
4. Internal:
When a type or type member is declared as internal, it can be accessed only within the same
assembly.
Example:
// Assembly1
class Student {
internal string name = "Sheeran";
}
// Assembly2
class Program {
static void Main(string[] args) {
// Accessing internal field from Assembly1
Console.WriteLine("Name: " + student.name);
}
}
In this example, the name field is internal, allowing access within the same assembly ( Assembly2 ).
5. Protected Internal:
The protected internal access modifier is a combination of protected and internal. It allows access
from the same assembly and the derived class of the containing class from any other assembly.
Example:
// Assembly1
public class Greet {
protected internal string msg = "Hello";
}
// Assembly2
class Program : Greet {
static void Main(string[] args) {
// Accessing protected internal field from Assembly1
Console.WriteLine(msg);
}
}
In this example, the msg field is protected internal, allowing access from the Program class in
Assembly2 .
6. Private Protected:
Example:
// Assembly1
public class StudentName {
private protected string name = "Sheeran";
}
In this example, the name field is private protected, allowing access from the derived class Program1 in
the same assembly.
Conclusion
Access modifiers are essential for controlling the visibility and accessibility of types and members in C#.
Choosing the appropriate access modifier ensures that code is secure, encapsulated, and follows the
principles of encapsulation and information hiding. Understanding these modifiers is crucial for writing
maintainable and well-structured C# code.
C# Variable Scope
In C#, the scope of a variable refers to the regions of code where the variable is accessible and can be
used. C# has three main types of variable scope: Class Level Scope, Method Level Scope, and Block
Level Scope.
using System;
namespace VariableScope {
class Program {
Console.ReadLine();
}
}
}
In this example, the variable str is accessible within the class, including the Display method.
using System;
namespace VariableScope {
class Program {
Console.ReadLine();
}
}
}
In this example, attempting to access the str variable from Method2 results in an error because str has
method level scope and is not accessible outside Method1 .
using System;
namespace VariableScope {
class Program {
public void Display() {
Console.ReadLine();
}
}
}
In this example, attempting to access the block level variable i outside the for loop results in an error
because i is only accessible within the block where it is declared.
C# Constructor
In C#, a constructor serves as a special method that is invoked when an object of a class is created. It
shares some similarities with methods, but there are key differences:
Creating a C# Constructor
A constructor is defined within a class with the same name as the class itself. It is invoked automatically
when an object of the class is created. Here's an example:
class Car {
// Constructor
Car() {
// Code inside the constructor
}
}
This line of code creates an object car1 of the Car class, invoking its constructor.
Types of Constructors
1. Parameterless Constructor
class Car {
// Parameterless constructor
Car() {
Console.WriteLine("Car Constructor");
}
}
2. Parameterized Constructor
A constructor can also accept parameters, making it a parameterized constructor. Example:
class Car {
string brand;
int price;
// Parameterized constructor
Car(string theBrand, int thePrice) {
brand = theBrand;
price = thePrice;
}
}
3. Default Constructor
If no constructor is defined, C# automatically creates a default constructor with an empty body.
Example:
class Program {
int a;
4. Copy Constructor
A copy constructor is used to create an object by copying data from another object. Example:
class Car {
// Copy constructor
Car(Car c1) {
brand = c1.brand;
}
}
5. Private Constructor
A constructor can be made private, limiting object creation to within the class. Example:
class Car {
// Private constructor
private Car() {
Console.WriteLine("Private Constructor");
}
}
6. Static Constructor
A constructor can be static. It is called automatically, and there can be only one per class. Example:
class Car {
// Static constructor
static Car() {
Console.WriteLine("Static Constructor");
}
}
Constructor Overloading
C# supports constructor overloading, where a class can have multiple constructors with different
parameter lists. Example:
class Car {
// Constructor with no parameter
Car() {
Usage:
By overloading constructors, a class can provide flexibility in object creation based on different scenarios.
C# this Keyword
In C#, the this keyword refers to the current instance of a class. It is primarily used to distinguish between
instance variables and parameters that share the same name. Here are some major uses of the this
keyword in C#:
using System;
namespace ThisKeyword {
class Test {
int num;
Test(int num) {
// this.num refers to the instance field
this.num = num;
Console.WriteLine("object of this: " + this);
}
using System;
namespace ThisKeyword {
class Test {
int num;
Test(int num) {
// this.num refers to the instance field
this.num = num;
}
By using this.num , the code unambiguously refers to the instance variable, ensuring clarity in the program.
3. Constructor Chaining
The this keyword is used to invoke one constructor from another, a concept known as constructor
chaining. For example:
using System;
namespace ThisKeyword {
class Test {
Here, this(33, 22) is used to call the constructor with two parameters from the constructor with one
parameter.
using System;
namespace ThisKeyword {
class Test {
int num1;
int num2;
Test() {
num1 = 22;
num2 = 33;
}
void display() {
// passing this as a parameter
passParameter(this);
}
In this example, passParameter(this) passes the current object to the passParameter method, allowing
access to the object's attributes.
using System;
namespace ThisKeyword {
class Student {
private string[] name = new string[3];
// declaring an indexer
public string this[int index] {
// returns the value of the array element
get {
return name[index];
}
// sets the value of the array element
set {
name[index] = value;
}
}
}
class Program {
Here, public string this[int index] defines an indexer, and the this keyword is used to reference the
object instance when accessing or setting values.
The this keyword plays a crucial role in maintaining clarity and avoiding ambiguity in code, especially in
scenarios involving similarly named variables and constructor chaining.
C# static Keyword
1. Static Variables
If a variable is declared static, it can be accessed using the class name. For instance:
using System;
namespace StaticKeyword {
class Student {
// static variable
public static string department = "Computer Science";
}
class Program {
static void Main(string[] args) {
// access static variable
Console.WriteLine("Department: " + Student.department);
Console.ReadLine();
}
}
}
In this example, the static variable department is accessed using the class name Student .
using System;
namespace StaticKeyword {
class Student {
static public string schoolName = "Programiz School";
public string studentName;
}
class Program {
static void Main(string[] args) {
Student s1 = new Student();
s1.studentName = "Ram";
Console.ReadLine();
}
}
}
In this program, schoolName is a static variable shared by all students, demonstrating efficiency.
3. Static Methods
Static methods can be called using the class name, and all objects of the class share the same static
method. For instance:
class Test {
public static void display() {....}
}
class Program {
static void Main(string[] args) {
Test.display();
}
}
Here, the static method display is accessed directly from the Program class using the class name.
using System;
namespace StaticKeyword {
class Test {
public void display1() {
Console.WriteLine("Non-static method");
}
public static void display2() {
Console.WriteLine("Static method");
}
}
In this example, display1 is a non-static method called using an object instance ( t1 ), while display2 is a
static method called using the class name.
5. Static Class
When a class is declared as static, no objects of the class can be created. All members within a static
class must also be static. Example:
using System;
namespace StaticKeyword {
static class Test {
static int a = 5;
static void display() {
Console.WriteLine("Static method");
}
Attempting to create an object of a static class results in an error, promoting the idea that static classes
cannot be instantiated.
using System;
namespace StaticKeyword {
class Test {
Here, static field age and static method display are accessed directly without using the class name.
The static keyword plays a crucial role in promoting memory efficiency and creating shared resources
across objects. Its usage ensures a single copy of type members shared by all instances, leading to
optimized program execution.
C# String
In C#, a string is a sequence of characters, represented by the string keyword. Strings are immutable,
meaning that once created, their values cannot be changed. The string class in C# provides various
methods to perform operations on strings.
namespace CsharpString {
class Test {
public static void Main(string[] args) {
// create string
string str1 = "C# Programming";
string str2 = "Programiz";
// print strings
Console.WriteLine(str1);
Console.WriteLine(str2);
Console.ReadLine();
}
}
}
In this example, two strings ( str1 and str2 ) are created and printed.
String Operations
using System;
namespace CsharpString {
class Test {
public static void Main(string[] args) {
// create string
string str = "C# Programming";
Console.WriteLine("string: " + str);
Console.ReadLine();
}
}
}
The Length property is used to find the total number of characters in the string.
using System;
namespace CsharpString {
class Test {
public static void Main(string[] args) {
// create strings
string str1 = "C# ";
Console.WriteLine("string str1: " + str1);
Console.ReadLine();
}
}
}
namespace CsharpString {
class Test {
public static void Main(string[] args) {
// create strings
string str1 = "C# Programming";
string str2 = "C# Programming";
string str3 = "Programiz";
Console.ReadLine();
}
}
}
Here, a new string is created by adding "World" to the original string "Hello ". The original string is then
released for garbage collection.
Here, the escape sequence \\" is used to include a double quote inside the string.
String Interpolation
String interpolation allows inserting variables inside a string using the $ character:
using System;
// string interpolation
string message = $"Welcome to {name}";
Console.WriteLine(message);
Console.ReadLine();
}
}
}
Here, the variable name is inserted into the string using {} braces within a string literal starting with $ .
Methods of C# string
Some commonly used string methods in C# are:
C# Inheritance
In C#, inheritance is a fundamental concept of Object-Oriented Programming (OOP) that enables the
creation of a new class (derived class) based on an existing class (base class). This promotes code reuse
Performing Inheritance in C#
In C#, the : symbol is used to denote inheritance. Here's a simple example:
class Animal {
// fields and methods
}
In this example, the Dog class is derived from the Animal class, inheriting its fields and methods.
Example: C# Inheritance
using System;
namespace Inheritance {
// base class
class Animal {
public string name;
class Program {
Console.ReadLine();
}
}
}
In this example, a subclass Dog is derived from the superclass Animal . The Dog class inherits the name
field and display() method from Animal . An object of the Dog class is then used to access both the
inherited and its own methods.
Types of Inheritance
1. Single Inheritance:
In single inheritance, a single derived class inherits from a single base class.
2. Multilevel Inheritance:
In multilevel inheritance, a derived class inherits from a base class, and then another class inherits
from this derived class.
3. Hierarchical Inheritance:
In hierarchical inheritance, multiple derived classes inherit from a single base class.
4. Multiple Inheritance:
Multiple inheritance is not supported in C#, but it can be achieved through interfaces.
5. Hybrid Inheritance:
Hybrid inheritance is a combination of two or more types of inheritance.
using System;
namespace Inheritance {
// base class
class Animal {
protected void eat() {
Console.WriteLine("I can eat");
}
}
Console.ReadLine();
}
}
}
In this example, the eat() method is declared as protected in the Animal class, and it can be accessed
from the Dog class.
using System;
namespace Inheritance {
// base class
class Animal {
public virtual void eat() {
Console.WriteLine("I eat food");
}
}
In this example, the eat() method in the Dog class overrides the same method in the Animal class.
using System;
namespace Inheritance {
// base class
class Animal {
public virtual void eat() {
Console.WriteLine("Animals eat food.");
}
}
In this example, the eat() method in the Dog class uses the base keyword to access the method of the
Animal class.
Importance of Inheritance in C#
Inheritance is crucial for promoting code reusability and establishing relationships between classes.
Consider an example where a RegularPolygon class has a method to calculate the perimeter, and Square
namespace Inheritance {
class RegularPolygon {
class Program {
In this example, the Square and Rectangle classes reuse the calculatePerimeter() method from the base
class RegularPolygon . This demonstrates how inheritance enhances code organization and reuse.
using System;
namespace AbstractClass {
Console.ReadLine();
In this example, Program is a class derived from the abstract class Language . The display() method of the
abstract class is accessed using an object of the Program class.
Abstract Method
An abstract method is a method without a body, marked with the abstract keyword. It must be present
inside an abstract class. A non-abstract class inheriting from an abstract class should provide an
implementation for all the abstract methods.
using System;
namespace AbstractClass {
class Program {
static void Main (string [] args) {
// create an object of Dog class
Dog obj = new Dog();
obj.makeSound();
Console.ReadLine();
}
}
}
In this example, the Animal abstract class has an abstract method makeSound() . The derived class Dog
namespace AbstractClass {
abstract class Animal {
protected string name;
// abstract method
public abstract string Name { get; set; }
}
class Program {
static void Main (string [] args) {
// create an object of Dog class
Dog obj = new Dog();
obj.Name = "Tom";
Console.WriteLine("Name: " + obj.Name);
Console.ReadLine();
}
}
}
In this example, the Name property of the Animal abstract class has abstract get and set accessors. The
derived class Dog provides an implementation for these accessors.
using System;
namespace AbstractClass {
abstract class Animal {
public Animal() {
Console.WriteLine("Animal Constructor");
}
}
class Program {
static void Main (string [] args) {
// create an object of Dog class
Dog d1 = new Dog();
Console.ReadLine();
}
}
}
In this example, both the Animal abstract class and the derived class Dog have constructors. When an
object of the Dog class is created, the constructor of the abstract class Animal is also called.
C# Abstraction
Abstraction is a key concept in object-oriented programming, and abstract classes are used to achieve it in
C#. Abstraction involves hiding unnecessary details and exposing only what is needed. It simplifies
complex systems by presenting a higher-level idea.
Example: C# Abstraction
using System;
namespace AbstractClass {
abstract class MotorBike {
public abstract void brake();
}
class Program {
Console.ReadLine();
}
}
}
In this example, the abstract class MotorBike has an abstract method brake() . The derived classes
SportsBike and MountainBike provide their own implementations of the brake() method. This demonstrates
C# Nested Class
In C#, a nested class is a class defined within another class. The nested class is also referred to as an
inner class. It encapsulates and organizes the code more effectively, providing a way to logically structure
classes within the scope of another class.
namespace CsharpNestedClass {
// outer class
public class Car {
// inner class
public class Engine {
public void displayEngine() {
Console.WriteLine("Engine: Petrol Engine");
}
}
}
class Program {
static void Main(string[] args) {
Console.ReadLine();
}
}
}
In the above program, the Engine class is nested inside the Car class. Objects of both the outer class
( Car ) and the inner class ( Engine ) are created to access their respective methods.
Now, these objects can be used to access the methods of their respective classes.
using System;
namespace CsharpNestedClass {
// outer class
public class Car {
public string brand = "Bugatti";
// nested class
class Program {
static void Main(string[] args) {
Console.ReadLine();
}
}
}
In this example, the Engine class accesses the brand field of the outer class Car by creating an object of
Car .
using System;
namespace CsharpNestedClass {
// outer class
public class Car {
//static member of outer class
public static string brand = "Bugatti";
// nested class
public class Engine {
public void display() {
Console.ReadLine();
}
}
}
In this example, the static field brand of the outer class Car is accessed directly inside the inner class
Engine .
using System;
namespace CsharpNestedClass {
// outer class
class Computer {
// derived class
class Laptop : Computer {
class Program {
static void Main(string[] args) {
Console.ReadLine();
}
}
}
using System;
namespace CsharpNestedClass {
// outer class
class Computer {
// nested class
public class CPU {
public void display() {
Console.WriteLine("Method of CPU class");
}
}
}
class Program {
static void Main(string[] args) {
Console.ReadLine();
}
}
}
In this example, the Laptop class is derived from the inner class CPU of the outer class Computer . The
inheritance syntax uses the name of the outer class along with the nested class.
Example 1:
Consider a project named HeightWeightInfo that represents height and weight information. In this
project, two files ( File1.cs and File2.cs ) contribute to a partial class named Record .
File1.cs
namespace HeightWeightInfo
{
class File1
{
}
File2.cs
namespace HeightWeightInfo
{
class File2
{
}
Program.cs
In this example, File1.cs and File2.cs contribute to the same Record class. The Record class is
instantiated in the Main method of Program.cs .
Key Points:
The partial keyword allows combining class attributes defined in various files into a single class.
All parts of the class should be in the same namespace and have the same access modifier.
Example 2:
Consider a partial class Car defined in File1.cs with a partial method InitializeCar() . Another part of
the class in File2.cs contains the implementation of InitializeCar() .
File1.cs
File2.cs
Key Points:
A partial method declaration consists of two parts: the definition and the implementation.
They may be in separate parts or the same part of the partial class.
Partial methods are implicitly private, have a return type of void, and cannot be virtual.
using System;
namespace SealedClass {
sealed class Animal {
class Program {
static void Main (string [] args) {
In the example, a sealed class Animal is defined. An attempt to derive the Dog class from the sealed
class results in an error, as a sealed class cannot have a derived class.
Key Points:
Sealed classes prevent inheritance, ensuring that no other class can derive from them.
using System;
namespace SealedClass {
class Animal {
public virtual void makeSound() {
Console.WriteLine("Animal Sound");
}
}
// Sealed method
sealed public override void makeSound() {
Console.WriteLine("Dog Sound");
}
}
class Program {
static void Main (string [] args) {
In the example, the makeSound() method is overridden inside the Dog class, and the method is sealed
using the sealed keyword. Attempting to further override this method in the Puppy class results in an
error.
Key Points:
Sealed classes are employed to avoid inheritance. This prevents manipulation of the methods
in the sealed class by other classes.
Example:
sealed class A {
// ...
}
2. Security Measures:
By sealing classes, security issues can be mitigated. Sealed classes ensure that methods
cannot be overridden, enhancing security.
3. Static Members:
Sealed classes are particularly useful when dealing with classes containing static members.
For instance, the Pens class in the System.Drawing namespace is a sealed class that has static
members representing pens with standard colors. Sealing such classes ensures that their
static members are not modified or manipulated.
Example:
C# Interface
In C#, an interface resembles an abstract class, but with a distinct feature: all methods within an
interface are fully abstract, meaning they lack a body. The interface keyword is employed to
create an interface. For instance:
interface IPolygon {
Implementing an Interface
Objects cannot be created from an interface; instead, other classes must implement it. Similar to
C# inheritance, the : symbol is used for interface implementation. Consider the example below:
using System;
namespace CsharpInterface {
interface IPolygon {
// Method without a body
void calculateArea(int l, int b);
}
class Program {
static void Main (string [] args) {
r1.calculateArea(100, 200);
}
}
}
In this example, the IPolygon interface is created with a method calculateArea(int l, int b) without
implementation. The Rectangle class then implements this interface, providing an implementation
for the calculateArea method.
namespace CsharpInterface {
interface IPolygon {
// Method without a body
void calculateArea(int a, int b);
}
interface IColor {
void getColor();
}
class Program {
static void Main (string [] args) {
r1.calculateArea(100, 200);
r1.getColor();
}
}
}
In this example, two interfaces, IPolygon and IColor , are created. The Rectangle class implements
both interfaces. Consequently, the Rectangle class must provide implementations for the methods
of both interfaces.
namespace CsharpInterface {
interface IPolygon {
// Method without a body
void calculateArea(int l, int b);
}
class Program {
static void Main (string [] args) {
r1.calculateArea(100, 200);
}
}
}
In this example, an interface named IPolygon is created with a method calculateArea(int l, int b)
without implementation. A reference variable of the interface IPolygon is then used, pointing to the
Rectangle class that implements it.
using System;
namespace CsharpInterface {
interface IPolygon {
// Method without a body
void calculateArea();
}
class Program {
static void Main (string [] args) {
In this program, an interface IPolygon is created with an abstract method calculateArea() . Two
classes, Square and Rectangle , implement the IPolygon interface. Each class provides an
independent implementation of the calculateArea() method. The program then demonstrates
creating objects of both classes and invoking their respective calculateArea() methods.
Advantages of C# Interface
Interfaces offer several advantages in C#:
1. Achieving Abstraction:
2. Specifications:
Interfaces provide specifications that a class must adhere to. For example, the IPolygon
interface specifies that any class implementing it must provide an implementation for the
calculateArea method.
Unlike classes, which cannot inherit from multiple classes, a class can implement multiple
interfaces.
4. Loose Coupling:
Interfaces promote loose coupling, meaning that changes in one part of the code have
minimal or no impact on other parts of the code. In the provided example, modifying the
implementation of calculateArea() in the Square class does not affect the Rectangle class.
C# Method Overloading
In C#, method overloading allows having two or more methods in a class with the same name but
different numbers, types, or order of parameters. This provides flexibility and improves code
readability. The return types of overloaded methods may differ, but they must have distinct
parameters.
using System;
namespace MethodOverload {
class Program {
Arguments: 100
Arguments: 100 and 200
In this example, the display() method is overloaded with different numbers of parameters. Based
on the number of arguments passed during the method call, the corresponding method is invoked.
using System;
namespace MethodOverload {
class Program {
Output:
In this example, the display() method is overloaded with different data types of parameters.
Depending on the type of arguments passed during the method call, the corresponding method is
executed.
using System;
namespace MethodOverload {
class Program {
Output:
int: 100
string: Programming
string: Programiz
int: 400
In this example, the display() method is overloaded by changing the order of parameters. The
method called depends on the order of arguments passed during the method call.
Method overloading provides a powerful mechanism for creating more readable and flexible code
by accommodating variations in method signatures based on different use cases.
C# Constructor Overloading
In C#, constructor overloading allows defining two or more constructors within the same class,
sharing the same name but differing in the number, types, or order of parameters. This provides
flexibility in creating instances of a class with varied initialization options.
using System;
namespace ConstructorOverload {
class Car {
Console.WriteLine();
Console.ReadLine();
}
}
}
Output:
Car constructor
In this example, the Car class has two constructors, one with no parameters and another with a
single string parameter. Depending on the arguments passed during the constructor call, the
corresponding constructor is invoked.
using System;
namespace ConstructorOverload {
class Car {
Console.WriteLine();
Console.ReadLine();
}
}
}
Output:
Brand: Lamborghini
Price: 50000
In this example, the Car class is overloaded with constructors having different types of
parameters. The appropriate constructor is called based on the type of arguments passed during
the constructor invocation.
namespace ConstructorOverload {
class Car {
Console.WriteLine();
Console.ReadLine();
}
}
}
Output:
Brand: Bugatti
Price: 50000
Speed: 60 km/hr
Color: Red
In this example, the Car class showcases constructor overloading with a different order of
parameters. The constructor called depends on the order of arguments passed during the
constructor invocation.
Constructor overloading in C# enhances the flexibility and usability of classes by allowing varied
ways to initialize objects based on the specific needs of the application.
namespace Program {
class Program1 {
static void Main(string[] args) {
Console.WriteLine("Hello World!");
}
}
}
Output:
Hello World!
In the above example, the line using System; imports the System namespace into the program,
allowing direct use of classes like Console . Without the using directive, the fully qualified name of
the Console class would be required:
namespace HelloWorld {
class Program {
static void Main(string[] args) {
Output:
Hello World!
In this example, an alias Programiz is created for System.Console , allowing the use of Programiz
instead of System.Console .
using System;
namespace Program {
class Program1 {
public static void Main(string[] args) {
double n = Sqrt(9);
Console.WriteLine("Square root of 9 is " + n);
}
}
}
Output:
Square root of 9 is 3
In this example, the line using static System.Math; allows direct access to the Sqrt() method from
the Math class. Without the using static directive, the fully qualified name would be required:
double n = Math.Sqrt(9);
The using static directive enhances code readability and conciseness by eliminating the need for
class qualification.
C# Type Conversion
Type conversion in C# involves the process of converting the value of one type (e.g., int, float,
double) to another type. There are two main types of type conversion in C#:
using System;
namespace MyApplication {
class Program {
static void Main(string[] args) {
int numInt = 500;
Type n = numInt.GetType();
// Implicit Conversion
double numDouble = numInt;
Type n1 = numDouble.GetType();
Output:
using System;
namespace MyApplication {
class Program {
static void Main(string[] args) {
// Explicit casting
int numInt = (int)numDouble;
Output:
using System;
namespace Conversion {
class Program {
static void Main(string[] args) {
string n = "100";
Output:
using System;
namespace Conversion {
class Program {
static void Main(string[] args) {
// create int variable
int num = 100;
Console.WriteLine("int value: " + num);
Console.ReadLine();
}
}
}
Output:
using System;
namespace Conversion {
class Program {
static void Main(string[] args) {
// create string variable
string str = "99.99";
Console.WriteLine("Original string value: " + str);
Console.ReadLine();
}
}
}
Output:
using System;
namespace Conversion {
class Program {
static void Main(string[] args) {
// create int variables
int num1 = 0;
int num2 = 1;
Console.ReadLine();
}
}
}
Output:
C# Preprocessor Directives
Preprocessor directives in C# are commands for the compiler that influence the compilation
process. They are processed before actual compilation begins, and they control which sections of
code are compiled or how specific errors and warnings are handled. These directives start with a
# (hash) symbol and last for one line, terminated by a new line.
#if preprocessor-expression
code to compile
#endif
2. #elif Directive
Used along with #if to check multiple preprocessor expressions.
Syntax:
#if preprocessor-expression-1
code to compile
#elif preprocessor-expression-2
code to compile
#endif
3. #else Directive
Used along with #if to create a compound conditional directive.
Syntax:
#if preprocessor-expression
code to compile
#elif
code to compile
#endif
4. #endif Directive
Indicates the end of a conditional directive.
#if preprocessor-expression
code to compile
#endif
5. #define Directive
Used to define a symbol.
Syntax:
#define SYMBOL
6. #undef Directive
Used to undefine a symbol.
Syntax:
#undef SYMBOL
7. #warning Directive
Generates a level 1 warning from the code.
Syntax:
#warning warning-message
8. #error Directive
Generates an error from the code.
Syntax:
#error error-message
9. #line Directive
Modifies the compiler's line number and filename for displaying errors and warnings.
Syntax:
Syntax:
Syntax:
#region region-description
codes
#endregion
Syntax:
using System;
namespace Directive
{
class ConditionalDirective
{
public static void Main(string[] args)
{
#if (CSHARP)
Console.WriteLine("CSHARP is defined");
#endif
}
}
}
In this example, the #define directive defines the symbol CSHARP . Inside the Main method, the #if
directive checks if CSHARP is true. If true, the code block inside the #if is compiled.
namespace Directive
{
class ConditionalDirective
{
static void Main(string[] args)
{
#if (TESTING)
Console.WriteLine("Currently Testing");
#elif (TRAINING)
Console.WriteLine("Currently Training");
#else
Console.WriteLine("Neither Testing nor Training");
#endif
}
}
}
In this example, the #elif directive is used along with #if to check multiple preprocessor
expressions. The code block inside the first true condition is compiled.
namespace Directive
{
class WarningError
{
public static void Main(string[] args)
{
#warning This is a warning message
#error This is an error message
}
}
}
In this example, the #warning directive generates a warning, and the #error directive generates an
error. The program terminates if an error is encountered.
namespace Directive
{
class RegionExample
In this example, the #region and #endregion directives create a region in the code that can be
expanded or collapsed when using a Visual Studio Code Editor.
namespace Directive
{
class PragmaExample
{
public static void Main(string[] args)
{
#pragma warning disable
#warning This is a warning 1
#pragma warning restore
#warning This is a warning 2
}
}
}
In this example, the #pragma warning disable directive disables warnings, and #pragma warning
restore enables warnings. Only the second warning is displayed on the output screen.
These examples demonstrate the usage of various C# preprocessor directives for conditional
compilation, organization, and special instructions for the compiler. Each directive serves a
specific purpose and enhances the flexibility and control over the compilation process.
Namespaces in C# Programming
In C#, namespaces are employed to organize and provide a level of separation for code
components. They serve as containers that can include other namespaces, classes, interfaces,
structures, and delegates. Namespaces play a crucial role in writing cleaner code and managing
larger projects.
Defining Namespace in C#
Namespaces are defined using the namespace keyword, with the syntax:
namespace NamespaceName
{
// Body of the namespace
}
For example:
namespace MyNamespace
{
class MyClass
{
public void MyMethod()
{
System.Console.WriteLine("Creating my namespace");
}
}
}
In this example, the MyNamespace namespace is created, containing a class MyClass with a method
MyMethod .
NamespaceName.MemberName
namespace MyNamespace
{
public class SampleClass
namespace MyProgram
{
public class MyClass
{
public static void Main()
{
MyNamespace.SampleClass.MyMethod();
}
}
}
Creating my namespace
In this example, a namespace MyNamespace is created, and its members are accessed from the
Main method within MyClass . The dot ( . ) operator is used to access the namespace's members.
For instance:
using System;
After including this line, you can use Console.WriteLine("Hello World!"); instead of the fully qualified
name System.Console.WriteLine("Hello World!"); .
Nested Namespace in C#
A namespace can contain another namespace, forming a nested namespace. The nested
namespace and its members are accessed using the dot ( . ) operator.
namespace MyNamespace
{
namespace NestedNamespace
{
// Body of nested namespace
namespace MyNamespace
{
namespace Nested
{
public class SampleClass
{
public static void MyMethod()
{
Console.WriteLine("Nested Namespace Example");
}
}
}
}
namespace MyProgram
{
public class MyClass
{
public static void Main()
{
MyNamespace.Nested.SampleClass.MyMethod();
}
}
}
C# Struct
In C#, a struct (structure) is similar to a class and is used to store data. However, unlike classes,
a struct is a value type.
Suppose we want to store the name and age of a person. We can create two variables, name and
age , to store values. However, if we want to store the same information for multiple people,
Define struct in C#
In C#, the struct keyword is used to define a struct. For example:
struct Employee
{
public int id;
}
Here, id is a field inside the struct. A struct can include methods, indexers, etc.
struct Employee
{
public int id;
}
In this example, a struct named Employee is created, and a variable emp of the struct Employee is
declared.
Access C# struct
A struct variable is accessed using the dot ( . ) operator to access its members. For example:
struct Employee
{
public int id;
}
Here, the variable emp of struct Employee is used with the dot ( . ) operator to access the id field
of the struct.
Note: Primitive data types like int , bool , and float are pre-defined structs in C#.
namespace CsharpStruct
{
// defining struct
struct Employee
{
public int id;
class Program
{
static void Main(string[] args)
{
// declare emp of struct Employee
Employee emp;
Console.ReadLine();
}
}
}
Output:
Employee Id: 1
In this program, a struct named Employee is created, which contains a field id and a method
GetId() . A variable emp of struct Employee is declared and used to access fields and methods of
the struct.
Note: We can also instantiate a struct using the new keyword. For example:
Here, this line calls the parameterless constructor of the struct and initializes all the members with
default values.
struct Employee
{
public int id;
// constructor
public Employee(int employeeId)
{
id = employeeId;
}
}
Note: C# version 9.0 or below does not allow creating parameterless constructors in a struct.
namespace CsharpStruct
{
// defining struct
struct Employee
{
public int id;
// parameterized constructor
public Employee(int employeeId, string employeeName)
{
id = employeeId;
name = employeeName;
}
}
class Program
{
static void Main(string[] args)
{
// calls constructor of struct
Employee emp = new Employee(1, "Brian");
Output:
In this example, a parameterized constructor is created inside the Employee struct. The constructor
assigns values to fields id and name . The constructor is called using the new keyword.
Note: Values for every field of a struct must be assigned inside the parameterized constructor. For
example:
// error code
public Employee(int employeeID, employeeName)
{
id = employeeID;
}
Here, the value for the name field is not assigned, and the code will generate an error.
Properties in C# struct
Properties can also be used inside a C# struct. For example:
using System;
namespace CsharpStruct
{
// defining struct
struct Employee
{
public int id;
// creates property
public int Id
{
// returns id field
get
{
return id;
}
// sets id field
set
class Program
{
static void Main(string[] args)
{
// calls the constructor of struct
Employee emp = new Employee();
emp.Id = 1;
Console.WriteLine("Employee Id: " + emp.Id);
Console.ReadLine();
}
}
}
Output:
Employee Id: 1
In this example, the Id property is created inside the Employee struct. The get method returns the
id field, and the set method assigns the value to the id field.
using System;
namespace CsharpStruct
{
// defining class
class Employee
{
public string name;
}
class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee();
Console.ReadLine();
}
}
}
Output:
Employee1 name: Ed
In this example, the value of emp1 is assigned to emp2 . The emp2 object refers to the same object
as emp1 . Therefore, an update in emp2 updates the value of emp1 automatically. This is why a
class is a reference type.
Contrary to classes, when we assign one struct variable to another, the value of the struct gets
copied to the assigned variable. So, updating one struct variable doesn't affect the other. For
example:
using System;
namespace CsharpStruct
{
//
defining struct
struct Employee
{
public string name;
}
class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee();
emp1.name = "John";
Console.ReadLine();
Output:
When we assign the value of emp1 to emp2 , a new value emp2 is created. The value of emp1 is
copied to emp2 , so a change in emp2 does not affect emp1 . This is why a struct is a value type.