Professional Documents
Culture Documents
C# (pronounced "C-Sharp") is a modern, object-oriented programming language developed by Microsoft. It is used for building a variety of applications, including Windows desktop
applications, games, mobile apps, and web applications. Some of the key features of the C# language include:
1. Object-Oriented Programming: C# is fully object-oriented, meaning that it supports encapsulation, inheritance, and polymorphism, which are the fundamental concepts of object-
oriented programming.
2. Type Safety: C# is a type-safe language, meaning that it enforces strict type checking to prevent type mismatches and other type-related errors. 3. Automatic Memory
Management: C# uses a garbage collector to automatically manage memory, freeing the programmer from manual memory management tasks.
4. LINQ and Lambda Expressions: C# supports LINQ (Language Integrated Query), which allows developers to query and manipulate data using a concise and expressive syntax. C# also
supports lambda expressions, which provide a concise way to write anonymous functions.
5. Asynchronous Programming: C# supports asynchronous programming through the a sync and await keywords, allowing developers to write asynchronous code that is easier to read and
maintain.
6. Strong Tooling Support: C# has strong tooling support from Microsoft and the .NET ecosystem, including Visual Studio, a popular integrated development environment (IDE)
that provides a rich set of features for C# development.
2. What do you mean by object orientation? Explain.
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and behavior. The objects interact with each other to form a
program.
OOP has several key concepts, including:
1. Encapsulation: The idea of bundling data and methods that work on that data within a single object. This is a way to protect the data from outside access and manipulation.
2. Inheritance: The ability of an object to inherit properties and behavior from a parent object. This allows for the creation of a new object based on an existing object, with the new object
inheriting the properties and behavior of the parent object.
3. Polymorphism: The ability of an object to take on multiple forms. This can be achieved through method overloading or method overriding.
4. Abstraction: The process of hiding the internal details of an object and exposing only the necessary information to the outside world. This allows for easier maintenance of the code and
reduces the impact of changes.
OOP has several benefits, including improved code reuse and modularity, the ability to model real-world objects, and a more intuitive and organized way of thinking about
code. It is a widely used programming paradigm and is supported by many programming languages, including C#, Java, Python, and others.
3. Difference between object oriented programming and object based programming.
C# has both keywords and identifiers to name variables, methods, classes, etc. Keywords are predefined, reserved words in C# that have special meaning and cannot be used as an
identifier (variable name, method name, class name, etc.). Examples of C# keywords include "int", "string", "var", "while", "if", "class", "new", "return", etc.
Identifiers are the names given to various elements in a C# program, such as variables, methods, classes, etc. Identifiers can be composed of letters, digits, and underscore characters, but
must start with a letter or an underscore. Identifiers are case sensitive and cannot be the same as a keyword. For example, "employee_count", "CalculateSum", "MyClass" are valid
identifier names in C#.
20.Differentiate parameters pass by value and by reference with examples.
int x = 10;
Console.WriteLine("Before increment: " + x);
IncrementByReference(ref x);
Console.WriteLine("After increment: " + x);
}
}
Output:
Before increment: 10
After increment: 11
21.What do you mean by operators? Explain different operators used in C# with examples.
Operators are symbols that perform specific operations on one or more operands. In C#, there are several types of operators:
1. Arithmetic Operators: used for mathematical operations such as addition, subtraction, multiplication, and division. Example: int x = 5 + 4;
2. Comparison Operators: used to compare two values and return a Boolean value. Example: bool result = (5 == 4);
3. Logical Operators: used to perform logical operations such as AND, OR, and NOT. Example: bool result = (5 < 4) && (6 > 5);
4. Assignment Operators: used to assign a value to a variable. Example: int x = 5; 5. Conditional Operators: used to perform a specific action based on a condition. Example: int x =
(5 > 4) ? 5 : 4;
6. Bitwise Operators: used to perform operations on individual bits of an integer value. Example: int x = 5 & 4;
7. Ternary Operators: used as shorthand for a simple if-else statement. Example: int x = (5 > 4) ? 5 : 4;
These are some of the commonly used operators in C#. Each operator has a specific purpose and can be used to perform a specific operation in your code.
22.Define operators precedence with example.
Operator precedence determines the order in which operations are performed in an expression. It is the set of rules that determines the order in which operations are performed when
evaluating an expression. In C#, some operators have higher precedence than others.
For example, in the expression 5 + 4 * 3, the multiplication operator * has higher precedence than the addition operator +. Therefore, the expression is evaluated as 5 + (4 * 3), resulting in
17.
Here is a table that shows the operator precedence in C#:
1. Parentheses ()
2. Unary operators (e.g. !, ++, --)
3. Multiplicative operators (*, /, %)
4. Additive operators (+, -)
5. Relational operators (>, <, >=, <=, ==, !=)
6. Logical operators (&&, ||)
7. Conditional operator ?:
8. Assignment operator =
It is important to understand operator precedence to write expressions that produce the expected result. If you want to override the operator precedence, you can use parentheses to group
operations together. For example, in the expression (5 + 4) * 3, the addition operator + is performed before the multiplication operator *, resulting in 27.
23.What do you mean by operators? Explain different operators used in C# with examples.
In C#, operators are symbols that perform specific operations on values, variables, and expressions. There are several types of operators in C#, including:
Arithmetic Operators: Arithmetic operators perform mathematical operations such as addition, subtraction, multiplication, division, and modulus. For example:
using System;
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 20;
int c = 0;
// Addition operator
c = a + b;
Console.WriteLine("a + b = " + c);
// Subtraction operator
c = a - b;
Console.WriteLine("a - b = " + c);
// Multiplication operator
c = a * b;
Console.WriteLine("a * b = " + c);
// Division operator
c = a / b;
Console.WriteLine("a / b = " + c);
// Modulus operator
c = a % b;
Console.WriteLine("a % b = " + c);
// Increment operator
a++;
Console.WriteLine("a++ = " + a);
// Decrement operator
b--;
Console.WriteLine("b-- = " + b); }
}
Comparison Operators: Comparison operators are used to compare two values and return a Boolean result indicating whether the comparison is true or false. For example: using System;
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 20;
// Equal to operator
Console.WriteLine("a == b: " + (a == b));
Logical Operators: Logical operators are used to perform logical operations such as AND, OR, and NOT. For example:
using System;
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 20;
int c = 30;
// Logical AND operator
Console.WriteLine("(a < b) && (b < c): " + ((a < b) && (b < c)));
// Logical OR operator
Console.WriteLine("(a < b) || (b > c): " + ((a < b) || (b > c)));
int b = 20;
// Simple assignment operator
a = b;
Console.WriteLine("a = " + a);
// Add and assign operator
a += b;
Console.WriteLine("a = " + a);
// Subtract and assign operator
a -= b;
Console.WriteLine("a = " + a);
// Multiply and assign operator
a *= b;
Console.WriteLine("a = " + a);
// Divide and assign operator
a /= b;
Console.WriteLine("a = " + a);
// Modulus and assign operator
a %= b;
Console.WriteLine("a = " + a);
}
}
Conditional Operators: Conditional operators are used to evaluate a condition and return one of two values based on whether the condition is true or false. For example: using System;
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 20;
// Conditional operator
int max = (a > b) ? a : b;
Console.WriteLine("Max Value: " + max);
}
}
Bitwise Operators: Bitwise operators are used to perform operations on individual bits within a value. For example:
int x = 5;
using System;
class Program
{
static void Main(string[] args)
{
int a = 60;
int b = 13;
// Bitwise AND operator
int and = a & b;
Console.WriteLine("Bitwise AND: " + and);
// Bitwise OR operator
int or = a | b;
Console.WriteLine("Bitwise OR: " + or);
{
if (numbers[i] > max)
max = numbers[i];
min = numbers[i];
Console.WriteLine("Max number in the array: " + max); Console.WriteLine("Min number in the array: " +
min); Console.ReadLine();
}
Console.WriteLine("Sorted numbers in ascending order: "); for (int i = 0; i < numbers.Length; i++)
Console.Write(numbers[i] + " ");
Console.ReadLine();
}
class Program
{
static void Main(string[] args)
{
int[,] matrix1 = new int[,] { { 1, 2 }, { 3, 4 } };
int[,] matrix2 = new int[,] { { 5, 6 }, { 7, 8 } };
Console.WriteLine("The product of the two matrices is: "); for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
Console.Write(result[i, j] + " ");
Console.WriteLine();
}
Console.ReadLine();
}
return result;
}
}
Write a C# program to add any two matrices.
using System;
class Program
{
static void Main(string[] args)
{
int[,] matrix1 = new int[,] { { 1, 2 }, { 3, 4 } }; int[,] matrix2 = new int[,] { { 5, 6 },
{ 7, 8 } };
Console.WriteLine("The sum of the two matrices is: "); for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
Console.Write(result[i, j] + " ");
Console.WriteLine();
}
Console.ReadLine();
{
for (int j = 0; j < A.GetLength(1); j++)
return result;
class Program
{
static void Main(string[] args)
{
string[] names = new string[] { "Ram", "Hari", "Pawan", "Deepak", "Shyam"}; Console.WriteLine("Original List of Names:");
foreach (string name in names)
Console.WriteLine(name);
Array.Sort(names);
Console.WriteLine("\nSorted List of Names:");
foreach (string name in names)
Console.WriteLine(name);
Console.ReadLine();
}
}
28.Write a C# program to find sum of 20 numbers in an array.
using System;
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
int sum = SumNumbers(numbers);
Console.ReadLine();
}
return sum;
}
}
29.What are control statements? Explain different Control statements with examples in details.
Control statements are the statements in C# that are used to control the flow of execution of a program based on certain conditions. There are different types of control statements in C#,
including:
If-else statement
Switch statement
For loop
While loop
Do-while loop
Foreach loop
Here's a detailed explanation of each control statement along with examples: If-else statement:
The if-else statement is used to execute a block of code based on the evaluation of a boolean expression. If the expression is true, the code inside the if block is executed, otherwise the
code inside the else block is executed.
Example:
int x = 10;
if (x > 5)
{
Console.WriteLine("x is greater than 5");
}
else
{
Console.WriteLine("x is not greater than 5");
}
Switch statement:
The switch statement is used to execute a block of code based on the value of a variable or expression. It is similar to the if-else statement, but it is more concise when dealing with
multiple conditions.
Example:
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
For loop:
The for loop is used to execute a block of code multiple times, until the specified condition is met. It consists of three parts: the initialization, the condition, and the increment/decrement.
Example:
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
While loop:
The while loop is used to execute a block of code as long as the specified condition is true. It first checks the condition before entering the loop.
Example:
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
}
Do-while loop:
The do-while loop is similar to the while loop, but it executes the block of code at least once before checking the condition. It checks the condition after entering the loop. Example:
int i = 0;
do
{
Console.WriteLine(i);
i++;
} while (i < 10);
Foreach loop:
The foreach loop is used to iterate through a collection of elements, such as an array or a list. It can be used to access each element in the collection one by one. Example:
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
These are the different control statements in C# and their examples. Understanding and using these control statements is an important aspect of programming. WAP to find largest among
three numbers.
using System;
namespace LargestNumber
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number: ");
int num2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the third number: "); int num3 =
Convert.ToInt32(Console.ReadLine()); int largest = num1;
if (num % 2 == 0)
{
Console.WriteLine(num + " is an even number."); }
else
{
Console.WriteLine(num + " is an odd number."); }
}
}
}
32.WAP whether a number is divisible by 7 or not using System;
namespace DivisibleBySeven
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
if (num % 7 == 0)
{
Console.WriteLine(num + " is divisible by 7.");
}
else
{
Console.WriteLine(num + " is not divisible by 7.");
}
}
}
}
33.WAP whether a number is exactly by 5 and 10
using System;
namespace DivisibleByFiveAndTen
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
A namespace is a way to organize code and provide a way to create globally unique type names. In C#, namespaces help to avoid naming collisions between different types in the same
application or between types from different libraries.
Here's a simple example that demonstrates the use of namespaces in C#: namespace MyApp.Models
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
}
namespace MyApp.Controllers
{
using MyApp.Models;
class StudentController
{
public void DisplayStudent(Student student)
{
Console.WriteLine("Id: " + student.Id);
Console.WriteLine("Name: " + student.Name);
}
}
}
class Program
{
static void Main(string[] args)
{
var student = new MyApp.Models.Student { Id = 1, Name = "Prabesh" }; var studentController = new MyApp.Controllers.StudentController();
studentController.DisplayStudent(student);
}
35.What do you mean by type conversion? Explain implicit and explicit conversion with example
Type conversion, also known as type casting, is the process of converting a value from one data type to another data type. There are two types of type conversions in C#: implicit and
explicit conversion.
1. Implicit Conversion: Implicit conversion is a type conversion that is performed automatically by the C# compiler, without the need for any explicit casting. The compiler will
automatically convert a value from one data type to another if the
target data type can safely accommodate the value of the source data type. For example:
int x = 10;
long y = x;
Here, the value of the integer variable x is implicitly converted to a long data type and stored in the variable y.
2. Explicit Conversion: Explicit conversion, on the other hand, requires a cast operator to be used to convert the value from one data type to another. An explicit conversion may result in
data loss if the target data type cannot safely accommodate the value of the source data type. For example:
double d = 10.5;
int i = (int)d;
Here, the value of the double variable d is explicitly converted to an integer data type and stored in the variable i. This conversion will result in a data loss, as the fractional part of the
number will be truncated.
In conclusion, type conversion is the process of converting a value from one data type to another data type. Implicit conversion is performed automatically by the C# compiler, while
explicit conversion requires the use of a cast operator and may result in data loss.
36.What is escape sequence. What are different escape sequence supported by C#? Explain.
An escape sequence is a combination of characters that represent a special character in C#. An escape sequence is denoted by a backslash (\) character, followed by another character. The
backslash character signals to the compiler that the character that follows is part of an escape sequence, not a regular character.
The following are the most commonly used escape sequences in C#: 1. \n: Represents a newline character. It is used to insert a line break in a string. 2. \r: Represents a carriage return character. It
is used to return the cursor to the beginning of the line, without advancing to the next line.
3. \t: Represents a horizontal tab character. It is used to insert a tab character in a string.
4. \': Represents a single quote (') character. It is used to include a single quote character within a string literal.
5. \": Represents a double quote (") character. It is used to include a double quote character within a string literal.
6. \\: Represents a backslash (\) character. It is used to include a backslash character within a string literal.
In conclusion, escape sequences are combinations of characters that represent special characters in C#. They are denoted by a backslash character followed by another character. Some of
the most commonly used escape sequences in C# include \n, \r, \t, \', \", and \\.
37.What is array? Differentiate rectangular and jagged array with example.
An array is a collection of variables of the same data type, stored in contiguous memory locations. Arrays in C# can be of two types: rectangular arrays and jagged arrays. 1. Rectangular
Array: A rectangular array is a two-dimensional array that has a fixed number of rows and columns. The elements of a rectangular array are stored in a grid-like structure, with each row
having the same number of columns. A rectangular array can be declared and initialized as follows:
int[,] arr = new int[3, 3]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
In this example, the rectangular array arr has 3 rows and 3 columns. 2. Jagged Array: A jagged array is an array of arrays. Each row of a jagged array can have a different number of elements. A
jagged array can be declared and initialized as follows:
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[3];
jagged[2] = new int[1];
In this example, the jagged array jagged has 3 rows. The first row has 2 elements, the second row has 3 elements, and the third row has 1 element.
In conclusion, arrays in C# can be of two types: rectangular arrays and jagged arrays. A rectangular array is a two-dimensional array that has a fixed number of rows and columns, while a
jagged array is an array of arrays, with each row having a different number of elements.
38.Write a C# program to compare any two strings.
Here is a sample C# program to compare two strings:
using System;
namespace StringComparisonExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter first string: ");
string str1 = Console.ReadLine();
Console.ReadLine();
}
}
}
In this program, the user is prompted to enter two strings. The string.Compare() method is used to compare the two strings, and the result is stored in the result variable. If the result is 0,
the strings are equal. If the result is less than 0, the first string is less than the second string. If the result is greater than 0, the first string is greater than the second string. The comparison
results are displayed on the console.
39.Write a C# program to demonstrate use of out and params modifier. Here is a sample C# program to demonstrate the use of out and params modifier:
using System;
namespace OutAndParamsModifierExample
{
class Program
{
static void Main(string[] args)
{
int result1;
int result2;
Console.WriteLine("Sum of " + num1 + " and " + num2 + " is: " + sum); Console.ReadLine();
}
}
}
In this program, two integer variables num1 and num2 are declared and initialized with values entered by the user. The sum of num1 and num2 is calculated and stored in the variable sum.
The result is then displayed on the console.
41. Write a program to find the product of two numbers.
Here is a simple C# program to find the sum, difference, product and division of two numbers:
using System;
namespace ArithmeticOperations
{
class Program
{
static void Main(string[] args)
{
int num1, num2;
int sum, difference, product, division;
Console.WriteLine("Sum of " + num1 + " and " + num2 + " is: " + sum); Console.WriteLine("Difference of " + num1 + " and " + num2 + " is: " + difference);
Console.WriteLine("Product of " + num1 + " and " + num2 + " is: " + product);
Console.WriteLine("Division of " + num1 + " and " + num2 + " is: " + division);
Console.ReadLine();
}
}
}
In this program, two integer variables num1 and num2 are declared and initialized with values entered by the user. The sum, difference, product and division of num1 and num2 are
calculated and stored in the respective variables. The results are then displayed on the console.
42.Explain the use of base keywords in C# with example.
Base keywords in C# are keywords that are reserved by the language and have a specific meaning. These keywords are used to perform specific operations and declare certain elements in
the code. They cannot be used as identifiers for naming classes, variables, methods, etc.
For example, the "base" keyword is used to access members of the base class from a derived class.
Consider the following example:
class Animal
{
public void Eat()
{
Console.WriteLine("Eating");
}
}
Class Struct
Reference type Value type
Can have a constructor, destructor, and all member Can only have a constructor (no destructor)
functions and limited member functions
Default value is the value of all its fields set to their default
Default value is null value
Allocated on the stack
Allocated on the heap
class Program
{
static void Main(string[] args)
{
Point p = new Point(10, 20);
p.Print();
Console.ReadKey();
}
}
In this example, a struct named Point is declared. It has two fields, X and Y, and a constructor that initializes those fields. The Print method displays the values of the fields.
The Main method creates an instance of the Point struct and calls the Print method to display its values.
44.Explain different access supported by C# with example.
C# supports the following access levels:
1. private: The member is accessible only within the same class. class Example
{
private int x = 10;
class Program
{
static void Main(string[] args)
{
Days today = Days.Monday;
Console.WriteLine(today);
Console.ReadKey();
}
}
In this example, an enum named Days is declared, which represents a set of days of the week. The Main method creates a variable of type Days named today and assigns it the value of
Days.Monday. The value of today is then displayed on the console. Note: By default, the first value in an enum is assigned the value 0, and each subsequent value is assigned the next
increment of the underlying integral type (either int or byte). It's possible to specify the underlying integral type for an enum and set specific values for the named constants.
46. What are different types of generic classes supported in C#? Explain with example.
C# supports three different types of generic classes:
1. Class: A generic class is a class that is parameterized over types. This means that a class can be declared with a placeholder for a specific type, and then used with actual types as
arguments.
Here's an example of a generic class in C#:
class GenericClass<T>
{
private T value;
public T GetValue()
{
return value;
}
}
In this example, the GenericClass is declared with a type parameter T. The T type parameter can be used as a placeholder for any type in the class. The class has a constructor that takes an
argument of type T and a GetValue method that returns an object of type T.
2. Struct: A generic struct is similar to a generic class, but it is a value type instead of a reference type.
Here's an example of a generic struct in C#:
struct GenericStruct<T>
{
private T value;
public GenericStruct(T value)
{
this.value = value;
}
public T GetValue()
{
return value;
}
}
In this example, the GenericStruct is declared with a type parameter T and has a constructor and a GetValue method that are similar to the generic class example. 3. Interface: A generic
interface is an interface that is parameterized over types. A class or struct can implement a generic interface by providing actual type arguments.
Here's an example of a generic interface in C#:
interface IGenericInterface<T>
{
T GetValue();
}
47. What do you mean by constructor? Explain different types of constructors in details along with program.
A constructor is a special type of method that is called automatically when an object of a class is created. It is used to initialize the fields or variables of the class and set their default
values. The name of a constructor is the same as the name of the class, and it does not have any return type, not even void.
There are several types of constructors in C#:
1. Default constructor: This constructor does not take any arguments, and it sets default values for the fields of the class. If a class does not have a constructor, the compiler
automatically generates a default constructor for the class. class Student
{
int id;
string name;
public Student()
{
id = 0;
name = "Unknown";
}
}
2. Parameterized constructor: This constructor takes arguments and initializes the fields of the class with the values passed as arguments.
class Student
{
int id;
string name;
public Student(Student s)
{
id = s.id;
name = s.name;
}
}
4. Private constructor: This constructor is declared with the private access modifier, and it is used to restrict the creation of objects of the class from outside the class. It is used to create a
singleton class, where only one instance of the class is allowed.
class Student
{
int id;
string name;
private Student()
{
id = 0;
name = "Unknown";
}
static Student()
{
count = 0;
}
}
48. What do you mean by generics? Write a c# program to create generic class and generic methods.
Generics is a feature in C# that enables creating classes, interfaces, and methods that can work with any data type. Instead of specifying a specific data type, you can use a type parameter,
which can be any data type that the client code specifies. Generics provide a way to create reusable code that can be adapted to different data types.
A generic class is created by using angle brackets < > and a type parameter, which is a placeholder for the data type that will be used in the class. The type parameter can be used to
declare fields, properties, and methods of the class.
Here is an example of a generic class in C#:
public class GenericClass<T>
{
private T value;
public T GetValue()
{
return value;
}
1. Compile-time Polymorphism (also known as method overloading): This type of polymorphism is achieved by using method overloading, where multiple methods with the same name
but different signatures exist within the same class. The appropriate method is chosen at compile-time based on the number and types of arguments passed to it.
class OverloadingDemo {
public void display(int num) {
System.out.println("The number is: " + num);
}
2. Run-time Polymorphism (also known as method overriding): This type of polymorphism is achieved by using method overriding, where a subclass provides a new implementation for a
method defined in its parent class. The appropriate method is chosen at run-time based on the type of the object being referred to.
class Shape {
public void draw() {
System.out.println("Drawing Shape");
}
}
50. What do you mean by inheritance? Explain different inheritance along with suitable programs.
Inheritance is a concept in Object-Oriented Programming (OOP) that allows one class to inherit properties and behaviors from another class. It enables code reusability and
promotes the idea of creating hierarchical class relationships.
Single Inheritance: A subclass inherits properties and behaviors from a single parent class.
class Shape {
public void draw() {
System.out.println("Drawing Shape");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
Multi-level Inheritance: A subclass inherits properties and behaviors from its parent class, which in turn inherits from its own parent class.
class Shape {
public void draw() {
System.out.println("Drawing Shape");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
class Shape {
public void draw() {
System.out.println("Drawing Shape");
}
}
class B {
public void displayB() {
System.out.println("Display B");
class C extends A, B {
public void displayC() {
System.out.println("Display C");
}
}
51. What is multiple inheritance? How it is achieved in C#? Explain with suitable example.
Multiple inheritance is a feature of object-oriented programming in which an object or class can inherit characteristics and features from more than one parent object or class.
C# does not support multiple inheritance directly, but it can be achieved through the use of interfaces. An interface is a collection of abstract members, such as properties, methods, and
events, that define a contract. A class can inherit from multiple interfaces, thus achieving the behavior of multiple inheritance.
Example:
using System;
interface IPrintable
{
void Print();
}
interface ISaveable
{
void Save();
}
class Document : IPrintable, ISaveable
{
public void Print()
{
Console.WriteLine("Printing document");
}
public void Save()
{
Console.WriteLine("Saving document");
}
}
52. What do you mean by interface? Explain the use of interface in C# with example.
An interface in C# is a blueprint for a class that defines a set of properties, methods, and events, but doesn't provide an implementation for them. It's a contract that specifies what members
a class must have, but leaves the actual implementation up to the class.
Interfaces are used to create a common set of properties, methods, and events for classes that implement them, allowing those classes to be used interchangeably in certain scenarios.
Example:
using System;
interface IPrintable
{
void Print();
}
class Document : IPrintable
{
public void Print()
{
Console.WriteLine("Printing document");
}
}
class Program
{
static void Main(string[] args)
{
IPrintable printable = new Document();
printable.Print();
}
}
53. What do you mean by abstraction? Explain the use of virtual function for method overriding.
Abstraction is a fundamental concept in object-oriented programming that refers to hiding the implementation details of a class and exposing only the necessary information to the outside
world. It's a way to encapsulate the complexity of an object, making it easier to use and understand.
In C#, virtual functions allow method overriding, which allows a subclass to provide a new implementation for a method defined in a base class. The virtual keyword is used in the base
class to indicate that the method can be overridden in a subclass.
Example:
using System;
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing shape");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing circle");
}
}
class Program
{
static void Main(string[] args)
{
Shape shape = new Circle();
shape.Draw();
}
}
54. Explain abstract class and method class with examples
Example:
abstract class Shape {
abstract double area();
}
class Rectangle extends Shape {
double width;
double height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double area() {
return width * height;
}
}
A method is a block of code that can be called by an object or class to perform a specific task. Methods are a fundamental part of object-oriented programming.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
}
55. Differentiate static and dynamic binding with examples
Method overloading is a feature in object-oriented programming languages, such as Java and C++, where multiple methods can have the same name but with different
parameters. This allows a class to have several methods with the same name, but with different numbers or types of parameters.
Method overloading is a powerful feature that allows you to write more concise and readable code, and it is commonly used in situations where multiple methods need to perform similar
operations with different inputs.
57.What is operator overloading? What are the different operators that can be overloaded in C#? Explain.
Operator overloading is a feature in C# that allows you to change the behavior of an operator for user-defined types. In other words, you can make an operator work with your custom data
type in a way that makes sense for that type. This allows you to create classes and objects that behave like built-in types, making them easier to work with in your code.
It's important to note that not all operators can be overloaded for all types. For example, you can't overload the conditional operator (?:), the null coalescing operator (??), or the conditional
access operator (?.) in C#.
When overloading an operator, you define a special method in your class or struct with the "operator" keyword, followed by the operator symbol. The method can have any access level,
but it must be either static or an instance method, depending on the type of the operator.
Here's an example of how you could overload the + operator for a custom class called ComplexNumber:
public class ComplexNumber
{
public double Real { get; set; }
public double Imaginary { get; set; }
It's important to use operator overloading with care, as it can make your code more complex and harder to understand. You should only overload operators when it makes sense for your
type, and you should always make sure that your overloaded operator behaves in a way that is intuitive and expected for your users.
A sealed method in C# is a method that cannot be overridden by a subclass. In other words, a sealed method acts as a final method in Java, which means that it cannot be overridden by
any subclass of the class that contains it.
The sealed method feature is useful when you want to prevent further modification of a method. For example, you might use a sealed method to define a method that provides critical
functionality and you want to ensure that it can't be overridden in any way.