DotNet Technology
1. Define copy constructor. Explain the use of copy constructor in C#.
➢ A copy constructor is a special type of constructor in C# that creates a
new object by copying the values of the members of an existing object of
the same class. The syntax for a copy constructor is as follows:
The copy constructor is typically used to create a new object that is a
copy of an existing object. For example, you might use a copy constructor
to create a new object that is a modified version of an existing object,
without modifying the original object.
A Copy constructor is a bit different from the normal constructors, as it
accepts an object of the same class as an argument, and the new object is
created by copying the values of the members of that object.
It is important to notice that if any object of the class has reference types
in it, the copy constructor will create only a shallow copy, it is a reference
of the same object, it will be not new object with new memory address.
To create a deep copy, we need to use the member wise clone method or
we can create our own deep copy method.
2. What are different access modifiers used in C#? Explain with examples.
➢ In C#, access modifiers are used to control the accessibility of class
members (fields, properties, methods, etc.). The four access modifiers
available in C# are:
public: A member marked as public can be accessed by any code in the
same assembly or another assembly that references the assembly in which
the member is defined.
Example:
public class MyClass {
public int myInt;
public void MyMethod() {}
}
private: A member marked as private can only be accessed by other
members of the same class in which it is defined.
Example:
class MyClass {
private int myInt;
private void MyMethod() {}
}
protected: A member marked as protected can only be accessed by other
members of the same class or a derived class.
Example:
class MyClass {
protected int myInt;
protected void MyMethod() {}
}
internal: A member marked as internal can be accessed by any code in the
same assembly, but not by code in another assembly.
Example:
internal class MyClass {
internal int myInt;
internal void MyMethod() {}
}
By default, if you don't specify any access modifier, it will be considered
as "private". For example, if a method or property doesn't need to be
accessed from outside the class, it should be marked as private. This helps
to ensure that the class's internal state is only modified by its own
methods and properties, which can help make your code more robust and
less error-prone.
3. How property is used on C# language? Compare automatic property with
other types of property with suitable example.
➢ In C#, properties are used to provide a way to access the fields of a class,
struct, or interface in a controlled manner. Properties are used to
encapsulate the data in an object, so that the data can be accessed and
modified in a consistent and controlled way.
There are three types of properties in C#:
i. Automatic Properties
ii. Read-Only Properties
iii. Write-Only Properties
An automatic property is a property that has a getter and a setter
automatically generated for it by the compiler. This is the simplest type of
property to create, as the compiler generates the underlying field and the
getter and setter methods for you.
Example:
class MyClass {
public int MyProperty { get; set; }
}
A read-only property has a getter but no setter. This type of property can
be set only in the constructor of the class.
Example:
class MyClass {
private int _myField;
public int MyProperty { get { return _myField; } }
public MyClass(int value) {
_myField = value;
}
}
A write-only property has a setter but no getter. This type of property can
be used to set a value, but the value cannot be read.
Example:
class MyClass {
private int _myField;
public int MyProperty { set { _myField = value; } }
}
Automatic properties are usually used in simple cases, when we don't
have any validation or logic during getting or setting values. In case you
have a complex logic or validation to set value of property, you can
consider using read-only or write-only property.
For example, when you want to add a validation that the value of a
property must be between 0 and 100, you can create a read-only property,
with a private backing field and validating the value before setting the
value.
Example:
class MyClass {
private int _myField;
public int MyProperty {
get { return _myField; }
set {
if (value>=0 && value<=100) {
_myField = value;
} else {
throw new ArgumentOutOfRangeException();
}
}
}
}
4. Define inheritance. Write a program in C# to demonstrate multilevel
inheritance.
➢ Inheritance is a mechanism in object-oriented programming that allows
one class to inherit the properties and methods of another class. The class
that inherits the properties and methods is called the derived class, and
the class that is being inherited from is called the base class.
In C#, a class can inherit from only one base class, but it can be a derived
class for multiple classes.
Multilevel Inheritance is a concept where a class can be derived from a
class, which is already derived from another class.
Here's an example of how to demonstrate Multilevel Inheritance in C#:
class Shape {
public int Width { get; set; }
public int Height { get; set; }
}
class Rectangle: Shape {
public int Area() {
return Width * Height;
}
}
class Square: Rectangle {
public int Perimeter() {
return 2 * (Width + Height);
}
}
In this example, the class Square is derived from the class Rectangle, and
the class Rectangle is derived from the class Shape. So, the class Square
inherits all the properties and methods of the class Shape and Rectangle.
You can also create an object of Square class and use the properties and
methods of Shape and Rectangle using the object.
class Program {
static void Main(string[] args) {
Square square = new Square { Width = 10, Height = 10 };
[Link]("Area of square is : " + [Link]());
[Link]("Perimeter of square is : " + [Link]());
}
}
In this example, Square class inherits the width and height property from
the Shape class, Area() method from Rectangle class and perimeter()
method from Square class.
5. What is the use of ‘throw’ keyboard? Explain with a proper example.
➢ The ‘throw’ keyword is used in C# to throw an exception. When an
exception is thrown, the execution of the program is interrupted and
control is passed to a catch block, where the exception can be handled.
The ‘throw’ keyword is typically used in a try-catch block, where the
code that might throw an exception is placed in the try block, and the
code that handles the exception is placed in the catch block.
Here's an example of how to use the ‘throw’ keyword in C#:
class DivideByZeroException : Exception {
public DivideByZeroException() : base("Divide by Zero exception.") {
}
}
class Calculator {
public int Divide(int a, int b) {
if (b == 0) {
throw new DivideByZeroException();
}
return a / b;
}
}
class Program {
static void Main(string[] args) {
Calculator calculator = new Calculator();
try {
int result = [Link](10, 0);
[Link](result);
} catch (DivideByZeroException ex) {
[Link]([Link]);
}
}
}
‘throw; keyword is useful to explicitly throw the exception when we
know that the code will fail under certain circumstances, and we want to
signal this failure to the calling code. It allows the program to handle the
error and continue execution in a controlled manner.
6. Define operator overloading? Write a C# program to overload a binary
operator.
➢ Operator overloading is a feature in C# that allows you to change the
behavior of operators when they are applied to objects of a certain class.
This allows you to define how operators such as +, -, *, / and others
should work with instances of your class, giving you more control over
how your class behaves.
Here is an example of how to overload the binary operator in C#:
using System;
namespace BinaryOverload {
class Calculator {
public int number = 0;
public Calculator() {}
public Calculator(int n)
{
number = n;
}
public static Calculator operator + (Calculator Calc1,
Calculator Calc2)
{
Calculator Calc3 = new Calculator(0);
[Link] = [Link] + [Link];
return Calc3;
}
public void display()
{
[Link]("{0}", number);
}
}
class CalNum {
static void Main(string[] args)
{
Calculator num1 = new Calculator(200);
Calculator num2 = new Calculator(40);
Calculator num3 = new Calculator();
num3 = num1 + num2;
[Link]();
[Link]();
[Link]();
}
}
}
7. Define enum. Explain it with proper example.
➢ An enum, short for enumeration, is a value type in C# that consists of a
set of named constants. Enums are used to represent a collection of
related values, such as the days of the week, the months of the year, or the
suits in a deck of cards. Each value in an enum is called an enumerator,
and each enumerator is represented by an integer value that is
automatically assigned by the compiler.
Example:
enum Days {
Sunday =1,
Monday =2,
Tuesday =3,
Wednesday =4,
Thursday =5,
Friday =6,
Saturday =7
}
class Program {
static void Main(string[] args) {
Days today = [Link];
[Link]("Today is " + today);
}
}
In this example, an enumerator is assigned to a variable of the enum type,
and then it prints the enumerator, in this case Monday.
Enums are very useful in situations where a variable can only take one of
a fixed set of values, or in situations where you want to use a more
meaningful name to represent an integer value, instead of using magic
numbers.
8. Explain Microsoft .NET framework and its components in detail.
Also explain about different types of constructors used in C#.
➢ The Microsoft .NET Framework is a software development framework
that provides a consistent programming model for building applications
on the Windows operating system. It consists of a large library of pre-
built code, called the Framework Class Library (FCL), which can be used
by developers to perform common tasks such as input/output, data access,
and network communication.
The .NET Framework provides a common runtime environment for
executing code, called the Common Language Runtime (CLR), that
abstracts away the underlying hardware and operating system. This
allows developers to write code using a high-level, object-oriented
programming model, and have it run on any machine that has the .NET
Framework installed.
Here are some of the main components of the .NET Framework:
The Common Language Runtime (CLR): is the runtime environment that
manages the execution of .NET code, providing features such as memory
management, type safety, security, and thread management. It also
provides a Just-in-Time (JIT) compiler that compiles intermediate
language (IL) code into machine code at runtime, allowing the code to
run on the specific architecture of the host machine.
The Framework Class Library (FCL): is a large library of pre-built code
that provides a wide range of functionality for developers, including data
access, network communication, UI controls, and more. The FCL is
organized into namespaces, which group related classes and types
together.
The C# language and the Visual Basic .NET languages: are the two main
languages supported by the .NET Framework, although the Framework
also supports many other languages such as F#, C++ and more. These
languages have their own specific syntax and features, but they all share
the same runtime environment provided by the CLR.
The [Link]: is a web development platform that allows developers to
build web applications, services and APIs using .NET, It provides a set of
classes and services for building web applications, including a web
server, web controls, and a programming model for building web pages.
Windows Communication Foundation (WCF) and Windows Workflow
Foundation (WWF): These are frameworks for building distributed
applications, WCF is designed for building service-oriented applications,
while WWF is designed for building workflows that model business
processes.
[Link]: This is a set of classes and services for working with data in a
.NET application. It provides a consistent programming model for
working with data, regardless of the data source, including relational
databases, XML files, and other data sources.
Windows Presentation Foundation (WPF): This is a framework for
building desktop applications with a rich user interface. It provides a set
of classes and services for building desktop applications, including a rich
set of UI controls and a programming model for building user interfaces.
All these components work together to provide a powerful and flexible
development platform, which allows developers to build a wide variety of
applications on the Windows operating system. With the .NET
Framework, developers can use a consistent programming model and a
large set of pre-built classes and services to simplify the development
process and focus on the business logic of their applications.
In C#, constructors are special methods that are executed when an
instance of a class is created. There are several types of constructors that
can be used in C#, which include:
Default Constructor: This is a constructor that takes no parameters, and is
automatically provided by the compiler if no other constructors are
defined in the class. The default constructor initializes the object's state
with the default values of the corresponding data types.
Example:
class MyClass {
public int x;
public MyClass() {}
}
Parameterized Constructor: This is a constructor that takes one or more
parameters, and allows the object's state to be initialized with specific
values when it is created. You can define as many constructors as you
need to meet the requirements of your class.
Example:
class MyClass {
public int x;
public MyClass(int value) {
x = value;
}
}
Copy Constructor: This is a constructor that creates a new object that is a
copy of an existing object. You can define a copy constructor by passing
the existing object as a parameter to the constructor, and then copying its
properties to the new object.
Example:
class MyClass {
public int x;
public MyClass(MyClass obj) {
x = obj.x;
}
}
Static Constructor :When a constructor is created using a static keyword,
it will be invoked only once for all of the instances of the class and it is
invoked during the creation of the first instance of the class or the first
reference to a static member in the class. A static constructor is used to
initialize static fields of the class and to write the code that needs to be
executed only once.
Example:
class employee
{
static employee(){}
}
Private Constructor: When a constructor is created with a private
specifier, it is not possible for other classes to derive from this class,
neither is it possible to create an instance of this class. They are usually
used in classes that contain static members only.
Example:
public class Counter
{
private Counter() {}
}
9. Define generics. Explain it with proper example. How virtual method is
used to achieve binding in C#? Explain with the help of suitable program.
➢ Generics is a feature in C# that allows you to write code that is not tied to
specific data types. This makes your code more reusable, more efficient,
and less error-prone.
With generics, you can define a class, a struct, an interface, a method or
delegate that can work with any data type, rather than being limited to a
specific data type. A generic type is defined with angle brackets < >
where you can specify the type parameter. Once defined, the type
parameter can be used as a placeholder for any specific data type.
Example:
using System;
public class GenericData<T>
{
public T data;
public void Add(T input) { data=input;}
public void Display()
{
[Link](data);
}
}
class TestGenericData
{
static void Main()
{
GenericData<int> data1 = new GenericData<int>();
[Link](1);
[Link]();
GenericData<string> list2 = new GenericData<string>();
[Link]("Steve");
[Link]();
}
}
In C#, a virtual method is a method that can be overridden by a derived
class. This allows you to change the behavior of the method in the
derived class, while still maintaining the same interface as the base class.
Virtual method is used to achieve runtime polymorphism also known as
dynamic binding.
When you call a virtual method on an object, the runtime system looks at
the actual type of the object, rather than the declared type of the variable,
to determine which version of the method to call. This process is known
as dynamic binding or runtime polymorphism.
Program:
class Shape {
public virtual double Area() {
return 0;
}
}
class Rectangle : Shape {
public int Width { get; set; }
public int Height { get; set; }
public override double Area() {
return Width * Height;
}
}
class Square : Rectangle {
public new double Area() {
return Width * Width;
}
}
Class Shap{
Static void Main(string[] args){
Shape shape = new Shape();
[Link]("Area of shape is : " + [Link]());
Shape rectangle = new Rectangle { Width = 4, Height = 5 };
[Link]("Area of rectangle is : " + [Link]());
Shape square = new Square { Width = 4 };
[Link]("Area of square is : " + [Link]());
}
}
10. What are method parameters? How can we pass the parameters by
references in C#? Also demonstrate the multiple inheritance in C#.
➢ In C#, method parameters are the values that are passed to a method when
it is called. These values are used by the method to perform its specific
task. Methods can have one or more parameters, and these parameters can
be of any data type, such as integers, strings, or custom classes.
In C#, by default, method parameters are passed by value. This means
that when you pass a value to a method, a copy of that value is made, and
the method operates on the copy. Any changes that the method makes to
the parameter do not affect the original value.
However, you can also pass parameters to a method by reference. When
you pass a parameter by reference, the method receives a reference to the
memory location of the original value, instead of a copy. Any changes
that the method makes to the parameter are made to the original value.
You can pass a parameter by reference by using the ‘ref’ keyword before
the parameter name in the method declaration. The ‘ref’ keyword must
also be used before the parameter name when the method is called.
Example:
class Example {
public static void Swap(ref int x, ref int y) {
int temp = x;
x = y;
y = temp;
}
}
class Program {
static void Main(string[] args) {
int a = 10, b = 20;
[Link]("Before swapping: a = {0}, b = {1}", a, b);
[Link](ref a, ref b);
[Link]("After swapping: a = {0}, b = {1}", a, b);
}
}
In C#, a class can inherit from only one base class, also known as single
inheritance. C# does not support multiple inheritance directly.
However, C# provides an alternative way to achieve multiple inheritance-
like functionality through interfaces. An interface is a contract that
specifies a set of methods, properties, and events that a class must
implement. A class can implement multiple interfaces, allowing it to
inherit the members of multiple interfaces.
Here is an example of how to achieve multiple inheritance in C# using
interfaces:
interface IRunnable {
void Run();
}
interface ISwimmable {
void Swim();
}
class Amphibian : IRunnable, ISwimmable {
public void Run() {
[Link]("Running");
}
public void Swim() {
[Link]("Swimming");
}
}
In this example, the ‘Amphibian’ class implements both the ‘IRunnable’
and ‘ISwimmable’ interfaces. As a result, it has access to the members of
both interfaces, ‘Run()’ and ‘Swim()’ methods.
[Link] LINQ can be used in C#? Write a program to select students whose
mask is greater than 50 and whose level is Bachelor using LINQ.
What are the differences between ADO and [Link]? Use
DataAdapter to read the records from a table.
➢ LINQ (Language Integrated Query) is a feature in C# that allows you to
perform complex data queries and operations using a simple, elegant
syntax that is similar to SQL. LINQ is integrated into the C# language, so
you can write LINQ queries using C# syntax, rather than having to learn a
separate query language.
Here is an example of how to use LINQ to select students whose marks
are greater than 50 and whose level is Bachelor:
class Student {
public string Name { get; set; }
public int Marks { get; set; }
public string Level { get; set; }
}
class Program {
static void Main(string[] args) {
List<Student> students = new List<Student>()
{
new Student{Name="Alice", Marks=78, Level="Bachelor" },
new Student{Name="Bob", Marks=55, Level="Masters" },
new Student{Name="Charlie", Marks=69, Level="Bachelor" },
new Student{Name="David", Marks=44, Level="PhD" },
new Student{Name="Eve", Marks=92, Level="Bachelor" },
};
var selectedStudents = from student in students
where [Link] > 50 && [Link] ==
"Bachelor"
select student;
foreach (var student in selectedStudents) {
[Link]([Link]);
}
}
}
In this example, we define a Student class, which has properties for name,
marks, and level. We create a list of Student objects and then use a LINQ
query to select students whose marks are greater than 50 and whose level
is "Bachelor".
A DataAdapter is a component in [Link] that is used to populate a
DataSet or a DataTable with data from a data source. It acts as a bridge
between the data source and a DataSet or DataTable, allowing you to
retrieve data from the data source and load it into a DataSet or DataTable,
and also to update the data source with any changes made to the DataSet
or DataTable.
Here's an example of how to use a DataAdapter to read records from a
table in a database:
using (SqlConnection connection = new
SqlConnection(connectionString))
{
string sql = "SELECT * FROM Students";
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, connection);
DataTable dataTable = new DataTable();
[Link](dataTable);
foreach (DataRow row in [Link])
{
[Link](row["Name"]);
}
}
In this example, we first create an instance of the SqlConnection class
with the connection string of our database. Then we create a new
SqlDataAdapter and we pass it a SQL statement for selecting all records
from the Students table and the SqlConnection. Next, we create a new
DataTable object, and use the Fill method of the SqlDataAdapter to fill
the DataTable with the data from the Students table.
[Link] a C# program to show delete and select operation in database.
What is multicast delegate? Explain with proper example.
➢ Here's an example of a C# program that performs a delete and select
operation on a database using [Link]:
using (SqlConnection connection = new
SqlConnection(connectionString))
{
// Open the connection
[Link]();
//Delete operation
string deleteSql = "DELETE FROM Students WHERE ID = @ID";
SqlCommand deleteCommand = new SqlCommand(deleteSql,
connection);
[Link]("@ID", 2);
int rowsDeleted = [Link]();
[Link](rowsDeleted + " rows were deleted.");
//Select operation
string selectSql = "SELECT * FROM Students";
SqlCommand selectCommand = new SqlCommand(selectSql,
connection);
SqlDataReader reader = [Link]();
while ([Link]())
{
[Link]("ID: " + reader["ID"] + ", Name: " +
reader["Name"]);
}
[Link]();
}
A multicast delegate is a type of delegate in C# that can invoke multiple
methods with a single delegate invocation. A delegate is a type-safe,
object-oriented implementation of a callback, and it's used to pass
methods as arguments to other methods.
A multicast delegate is created by combining multiple delegate instances
using the "+" operator. When the multicast delegate is invoked, all of the
methods it references are invoked in the order they were added.
Example:
using System;
namespace Program
{
public delegate void delmethod(int x, int y);
public class MultipleDelegate
{
public void Add(int x, int y)
{
[Link]("Sum is {0}", x + y);
}
public void Subtract(int x, int y)
{
[Link]("Difference is {0}", x - y);
}
}
class Sample
{
static void Main(string[] args)
{
MultipleDelegate obj = new MultipleDelegate();
delmethod del = new delmethod([Link]); // Here we have multicast
del += new delmethod([Link]); // Add and subtract are called
del(50, 10);
del -= new delmethod([Link]); //Only subtract is called
del(20, 10);
[Link]();
}
}
}