Construcrtor
Construcrtor
class Car
// Default Constructor
public Car()
Model = "Unknown";
Year = 2000;
// Parameterized Constructor
Model = model;
Year = year;
class Program
}
METHOD OVERLOADING:
class Calculator
return a + b;
return a + b + c;
return a + b;
class Program
}
Explain loops in C#.
In C#, loops are used to repeat a block of code multiple times based on a condition. There are several
types of loops in C#, each serving different purposes:
Syntax:
Example:
while loop: Used when the condition is checked before each iteration, and the loop runs as long as
the condition remains true.
Syntax:
while (condition)
{
// Code to execute
}
Example:
int i = 0;
while (i < 5)
{
Console.WriteLine(i); // Output: 0 1 2 3 4
i++;
}
do-while loop: Similar to the while loop, but the condition is checked after the loop is executed, so it
always runs at least once.
Syntax:
do
{
// Code to execute
} while (condition);
Example:
int i = 0;
do
{
Console.WriteLine(i); // Output: 0 1 2 3 4
i++;
} while (i < 5);
foreach loop: Used to iterate through each element in a collection, such as an array or list.
Syntax:
Example:
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num); // Output: 1 2 3 4 5
}
Key Differences: