You are on page 1of 6

Write a C# code snippet to add any generics and collections.

using System;

namespace AddNumbers

class Program

static void Main(string[] args)

Console.WriteLine(Add<int>(3, 5));

Console.WriteLine(Add<float>(3.5f, 5.6f));

Console.WriteLine(Add<double>(3.5, 5.6));

Console.ReadLine();

static T Add<T>(T a, T b)

return (dynamic)a + (dynamic)b;

In C#, you can create a customized exception by defining a new exception class that derives from the
System.Exception class. The new exception class can include additional properties and methods
to provide more information about the error that occurred.

using System;

namespace CustomExceptionExample
{

class InvalidAgeException : Exception

public InvalidAgeException() : base("Invalid Age")

public InvalidAgeException(string message) : base(message)

class Program

static void Main(string[] args)

try

int age = -5;

if (age < 0)

throw new InvalidAgeException("Age cannot be negative.");

catch (InvalidAgeException ex)

Console.WriteLine(ex.Message);

Console.ReadLine();

}
Employee pay roll

using System;

public class Employee

private int id;

private string name;

private double salary;

public Employee(int id, string name, double salary)

this.id = id;

this.name = name;

this.salary = salary;

public int Id

get { return id; }

set { id = value; }

public string Name

get { return name; }

set { name = value; }

public double Salary

get { return salary; }


set { salary = value; }

public override string ToString()

return "ID: " + id + ", Name: " + name + ", Salary: " + salary;

public static Employee operator +(Employee e1, Employee e2)

return new Employee(0, "Total", e1.salary + e2.salary);

public class Manager : Employee

private double bonus;

public Manager(int id, string name, double salary, double bonus) : base(id, name, salary)

this.bonus = bonus;

public double Bonus

get { return bonus; }

set { bonus = value; }

public override string ToString()

{
return base.ToString() + ", Bonus: " + bonus;

class Program

static void Main(string[] args)

Employee e1 = new Employee(1, "John", 5000);

Employee e2 = new Employee(2, "Jane", 6000);

Manager m1 = new Manager(3, "Bob", 7000, 1000);

Manager m2 = new Manager(4, "Alice", 8000, 2000);

Employee total = e1 + e2 + m1 + m2;

Console.WriteLine(e1);

Console.WriteLine(e2);

Console.WriteLine(m1);

Console.WriteLine(m2);

Console.WriteLine(total);

Console.ReadKey();

You might also like