C# Core OOP Concepts
Q1. Write a console program that print helloworld using command line argument.
Problem Explanation
This program demonstrates how to pass arguments to a C# console application from the command line and display them. Command-line arguments are useful for passing runtime configuration to programs.
Step-By-Step Instructions
- Create a console application in Visual Studio
- Access the args array in the Main method
- Print arguments passed from command line
- Build the application
- Run from command line with arguments
Code
using System;
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Hello World");
}
else
{
foreach (string arg in args)
{
Console.WriteLine("Hello " + arg);
}
}
}
}
Output
Key Concept
The Main method signature includes a string[] args parameter that receives command-line arguments. This allows programs to be configurable without recompilation, making them more flexible for different use cases.
Q2. Write a console application program to demonstrate switching statement.
Problem Explanation
The switch statement allows selection among multiple options based on a single expression value. It's more efficient than multiple if-else statements for checking a single variable against multiple values.
Step-By-Step Instructions
- Get user input (day number or character)
- Use switch statement with expression
- Add case labels for each possible value
- Add break statement in each case
- Add default case for unmatched values
Code
using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter day number (1-7):");
int day = int.Parse(Console.ReadLine());
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
}
}
Output
Key Concept
Switch statements are cleaner alternatives to multiple if-else statements. The break statement prevents fall-through to the next case. The default case handles unexpected values, making programs more robust.
Q3. Write a console application for swapping two numbers using pass by value.
Problem Explanation
Pass by value creates a copy of the variable and passes it to the function. Changes inside the function do not affect the original variable. This demonstrates the difference from pass by reference.
Step-By-Step Instructions
- Create two integer variables with values
- Create a function that accepts parameters by value
- Swap values inside the function
- Observe that original values remain unchanged
- Display results before and after function call
Code
using System;
class Program
{
static void Swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
Console.WriteLine("Inside method: a=" + a + ", b=" + b);
}
static void Main()
{
int x = 10;
int y = 20;
Console.WriteLine("Before swap: x=" + x + ", y=" + y);
Swap(x, y);
Console.WriteLine("After swap: x=" + x + ", y=" + y);
}
}
Output
Key Concept
Pass by value creates copies of variables. Modifications inside the function affect only the copy, not the original. This is the default behavior in C# for value types (int, float, etc.).
Q4. Write a Console application for swapping of two numbers using pass by reference.
Problem Explanation
Pass by reference uses the 'ref' keyword to pass a reference to the original variable. Changes made inside the function affect the original variable.
Step-By-Step Instructions
- Create two integer variables
- Create function with 'ref' keyword parameters
- Swap values using temporary variable
- Original variables will be modified
- Display results to confirm swap
Code
using System;
class Program
{
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
Console.WriteLine("Inside method: a=" + a + ", b=" + b);
}
static void Main()
{
int x = 10;
int y = 20;
Console.WriteLine("Before swap: x=" + x + ", y=" + y);
Swap(ref x, ref y);
Console.WriteLine("After swap: x=" + x + ", y=" + y);
}
}
Output
Key Concept
The 'ref' keyword enables pass by reference. It allows functions to modify the original variables. This is useful when you need to return multiple values or modify parameters.
Q5. Write a C# Program that uses explicit keyword.
Problem Explanation
The explicit keyword prevents automatic type conversion (implicit conversion). It requires explicit casting, making the code safer by preventing unintended type conversions.
Step-By-Step Instructions
- Create a custom class with operator overloading
- Define explicit conversion operator
- Require explicit cast syntax for conversion
- Demonstrate the conversion in Main method
Code
using System;
class Temperature
{
public double Celsius { get; set; }
public Temperature(double celsius)
{
Celsius = celsius;
}
public static explicit operator Fahrenheit(Temperature c)
{
return new Fahrenheit((c.Celsius * 9/5) + 32);
}
}
class Fahrenheit
{
public double Value { get; set; }
public Fahrenheit(double f)
{
Value = f;
}
}
class Program
{
static void Main()
{
Temperature celsius = new Temperature(25);
Fahrenheit fahrenheit = (Fahrenheit)celsius;
Console.WriteLine("25°C = " + fahrenheit.Value + "°F");
}
}
Output
Key Concept
Explicit conversions require visible casting in the code. This makes the intent clear and prevents accidental type conversions. It's safer than implicit conversion for user-defined types.
Q6. Write a c# program to demonstrate inheritence.
Problem Explanation
Inheritance allows a derived class to inherit properties and methods from a base class. This promotes code reuse and establishes hierarchical relationships between classes.
Step-By-Step Instructions
- Create a base class with properties and methods
- Create a derived class that inherits from base
- Add additional properties/methods to derived class
- Override base class methods if needed
- Create objects and demonstrate inheritance
Code
using System;
class Animal
{
public string Name { get; set; }
public void Eat()
{
Console.WriteLine(Name + " is eating");
}
public virtual void Sound()
{
Console.WriteLine("Generic animal sound");
}
}
class Dog : Animal
{
public override void Sound()
{
Console.WriteLine(Name + " barks: Woof Woof");
}
}
class Program
{
static void Main()
{
Dog dog = new Dog();
dog.Name = "Buddy";
dog.Eat();
dog.Sound();
}
}
Output
Key Concept
Inheritance uses a colon (Animal : Dog) syntax. The virtual keyword allows method overriding. Derived classes inherit all public members of the base class and can extend or override their behavior.
Q7. Write a C# program to demonstrate interface.
Problem Explanation
Interfaces define a contract for implementing classes. They specify which methods and properties a class must have without providing implementation. This enables polymorphism and loose coupling.
Step-By-Step Instructions
- Define an interface with method signatures
- Create classes implementing the interface
- Implement all interface methods
- Create objects through interface references
- Demonstrate polymorphic behavior
Code
using System;
interface IShape
{
void Draw();
double CalculateArea();
}
class Circle : IShape
{
public double Radius { get; set; }
public void Draw()
{
Console.WriteLine("Drawing Circle");
}
public double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
class Rectangle : IShape
{
public double Width { get; set; }
public double Height { get; set; }
public void Draw()
{
Console.WriteLine("Drawing Rectangle");
}
public double CalculateArea()
{
return Width * Height;
}
}
class Program
{
static void Main()
{
Circle c = new Circle { Radius = 5 };
c.Draw();
Console.WriteLine("Area: " + c.CalculateArea());
Rectangle r = new Rectangle { Width = 10, Height = 20 };
r.Draw();
Console.WriteLine("Area: " + r.CalculateArea());
}
}
Output
Key Concept
Interfaces define contracts without implementation. Classes implementing interfaces must provide all required members. This enables polymorphism where different classes implement the same interface differently.
Q8. Write a c# program to demonstrate abstract class.
Problem Explanation
Abstract classes are incomplete classes that cannot be instantiated directly. They serve as templates for derived classes and can contain both abstract methods (without implementation) and concrete methods.
Step-By-Step Instructions
- Create an abstract base class
- Define abstract methods (no implementation)
- Create derived classes from abstract class
- Implement all abstract methods in derived classes
- Cannot instantiate abstract class directly
Code
using System;
abstract class Vehicle
{
public string Brand { get; set; }
public abstract void Start();
public abstract void Stop();
public void Honk()
{
Console.WriteLine("Honk Honk!");
}
}
class Car : Vehicle
{
public override void Start()
{
Console.WriteLine(Brand + " car engine started");
}
public override void Stop()
{
Console.WriteLine(Brand + " car engine stopped");
}
}
class Program
{
static void Main()
{
Car car = new Car { Brand = "Toyota" };
car.Start();
car.Honk();
car.Stop();
}
}
Output
Key Concept
Abstract classes define the interface for subclasses but leave some details to be implemented by subclasses. They can have both abstract methods (must be overridden) and concrete methods (can be inherited as-is).
Q9. Write a C# program to partial class.
Problem Explanation
Partial classes allow a single class definition to be split across multiple files. This is useful for separating auto-generated code from user code in large projects.
Step-By-Step Instructions
- Create first part of class with 'partial' keyword
- Add methods and properties to first part
- Create second file with same class name as 'partial'
- Add more methods to second part
- Both parts compile as single class
Code - File 1: Employee.cs
using System;
partial class Employee
{
public string Name { get; set; }
public int Id { get; set; }
public void DisplayInfo()
{
Console.WriteLine("Name: " + Name);
Console.WriteLine("ID: " + Id);
}
}
Code - File 2: Employee_Methods.cs
using System;
partial class Employee
{
public void CalculateSalary(double hourlyRate, int hours)
{
double salary = hourlyRate * hours;
Console.WriteLine("Salary: " + salary);
}
}
Code - Main Program
using System;
class Program
{
static void Main()
{
Employee emp = new Employee { Name = "John", Id = 101 };
emp.DisplayInfo();
emp.CalculateSalary(25, 40);
}
}
Output
Key Concept
Partial classes enable separation of concerns. Auto-generated code (like from designers) can be kept separate from user-written code. All partial declarations compile into a single class at compile time.