0% found this document useful (0 votes)
100 views

C# Interview Question

C# is an object-oriented programming language developed by Microsoft that is compiled to .NET intermediate language. The public access modifier makes an element accessible anywhere, while static makes it globally accessible without object instantiation. An object pool stores commonly used objects to reduce resource usage when objects are created and destroyed. A delegate stores a reference to a method and helps implement encapsulation. Constructors cannot be overridden in C#, and base constructors are always called first. Namespaces help organize code by preventing naming collisions between identically named classes in different namespaces.

Uploaded by

Audumbar Meher
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views

C# Interview Question

C# is an object-oriented programming language developed by Microsoft that is compiled to .NET intermediate language. The public access modifier makes an element accessible anywhere, while static makes it globally accessible without object instantiation. An object pool stores commonly used objects to reduce resource usage when objects are created and destroyed. A delegate stores a reference to a method and helps implement encapsulation. Constructors cannot be overridden in C#, and base constructors are always called first. Namespaces help organize code by preventing naming collisions between identically named classes in different namespaces.

Uploaded by

Audumbar Meher
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

1. What is C#?

C# is a simple, modern, general-purpose, object-oriented programming language


developed by Microsoft. It is type-safe and managed language that is compiled by
the Roslyn .NET compiler to generate Microsoft intermediate language (machine
code).

2. Differentiate between static and public?


The public access modifier in C# states the compiler that the element is accessible
by any other element in the same or other class.

When a member in C# has the Static access modifier in front of it, such as static
method, static variable, or static parameters, it means that the element has global
access and any other element can access it using class directly. You don't need to
create an instance of the class to access that element. The compiler stores the
address of the method as the entry point and uses this information to begin
execution before any objects are created.

3. What is an object pool?


● An object pool is a container built to keep the most used objects for faster
access and use.
● An object pool is based on the object pool design pattern in which instead of
every time creating objects when needed, commonly used objects are created
beforehand and kept in an easily accessible location. This is done to reduce
the cost of the application as creating objects can use a lot of resources and
can sometimes lead to the slowness of the .NET application.
● The objects of the pool are returned to the pool, once the use is over, thus
making it efficient to reuse them. If the object is not in the pool, it is then
created when needed as a normal object.
4. What is a delegate?

A delegate is a reference type entity that is used to store the reference of a method.
So whenever you need to call a method, you can easily use the delegate by
initialising a pointer to that method, thereby helping to implement
Encapsulation.Delegates in C# are similar to function pointers in C/C++ and can be
used to pass methods as arguments to other methods, chained together, or even can
be used to call methods on events

Can we override a constructor?

No, in C#, it is necessary to define properly which constructor you are trying to call to
instantiate a class and what arguments are being passed. So you cannot override a
constructor in C#.

6. Which constructor is called first in C#?


Base Constructor is always called first in C#, followed by Derived class constructor.

7. How many types of constructors can a class have?


Like functions, a class can have any number of constructors. But unlike functions, all
the constructors will have the same name, the name of the class, but different
parameter signatures. In other words, you can create as many valid overloads of a
constructor, as you want.

8. What is a namespace?
Namespace in C# can be considered as a container in which you can define classes,
methods, interfaces, structures, or other child namespaces, such that classes with
the same name but different namespaces won’t cause any error. In C#, namespaces
are an efficient entity to organize codes for larger applications.

The major advantages of Namespace are:


● Namespaces help in effectively organizing large C# code projects.
● To use any entity in a namespace, simply use <namespace name>.<entity
name>
● No two classes with the same name in a different namespace will cause any
error.

9. How to declare a private constructor in C#?


In C#, if you don’t specify any access specifier against a constructor, that
constructor is by default specified as a public constructor by the compiler.

10. Give examples of I/O classes?

Some of the important input-output classes are:

I/O Class Description

FileStream For input-output in a file.

BinaryReader For reading data from a binary


stream.

BinaryWriter For writing data in binary format.


File For manipulating files.

StreamReader For reading characters from a stream.

StreamWriter For writing characters into a stream.

StringReader For reading characters from a string


buffer.

StringWriter For writing characters into a string


buffer.
Directory For manipulating a directory structure.

DirectoryInfo For performing operations on


directories.

11. What is the difference between ref and out keywords?

● ref keyword is used to pass an already initialized variable to a method as a


reference type, facilitating bi-directional data passing.

Why are strings in c# immutable?


In C# Arrays have a fixed size, which means that once an array is created of some
size, it cannot be dynamically increased or decreased in size. The CLR (Common
Language Runtime) in C#, stores the strings as an array of characters. So whenever
we delete or add a character or characters to a string, the original arrays of
characters are fixed, and hence a new array of characters is created to
accommodate the change. This is known as the immutability of strings in C#.

13. What is the need for Encapsulation?


Encapsulation is the process of binding an entity with its implementation with the
aim of data hiding. It is done to hide the irrelevant details from a user, and show only
the process which the user needs. By doing so, we hide the implementation details
of entities and thereby help users to understand the higher-level design of the code
easily, without getting bothered about the implementation details.

Encapsulation has some hidden advantages as well which make it the need of the
hour for every software developer such as preventing accidental corruption,
unauthorized access to entities, etc.

How will you implement Encapsulation?


Encapsulation is done with the help of access modifiers in C#: public, private,
protected, and default.

Scope of an element with the private


pub prote inter protected priv
access specifier / Access protecte
lic cted nal internal ate
specifiers d

Entire program Yes No No No No No

Containing class Yes Yes Yes Yes Yes Yes

Current assembly Yes No Yes Yes No No

Derived types Yes Yes No Yes No No


Derived types within the Yes Yes Yes Yes No Yes
current assembly

15. What are Access Modifiers in C# And Why are they important?
As the name suggests, access modifiers are keywords that define the scope of
entities in a C# code, as to which point an entity can be accessed from its point of
creation.

In particular, there are 4 access modifiers in C#: public, protected, internal, and
private.

17. What is the use of the method "hiding" in inheritance?

Method hiding or Method shadowing is used to hide the implementation of the base
class method under the shadow of the child class method, with the help of a new
keyword.

This is done to clear the ambiguity when the child class has a method with the same
name as that of the base class and hence helps in abstraction.

18. State the uses of Reflection in C#


Reflection is the process of describing the metadata of types, methods, and fields in
a code.

Some of the major use of Reflection in C#:

● Load assemblies at the given runtime


● Help to learn about the definition of entities like class, or enumeration by
groups
● Get to know about fields, properties, constructors, events, and methods in a
Class
● Helps to learn about the properties of entities such as their types, read-only
status, etc.
● Helps in getting and setting a property’s value
● Helps to learn about an entity’s attributes.

19. What is Framework targeting in C# and what is the use of it?


Framework targeting in C# is used to mention the version of the .NET framework
that the project is intended to run upon.

Framework targeting helps guarantee that the application uses only functionality that
is available in the specified framework version.

20. How to specify what version of the framework your application is


targeting?
In the configuration file, just use the targetFramework attribute to specify the
version of ASP.NET that your application is targeting.

23. What is the difference between a struct and a class in C#?

Struct Class
Structs are value-type entities stored Class is a reference type entity
in stack memory. stored in heap memory.

Allocation and de-allocation of Allocation and de-allocation of


Structs are cheaper when the size of Classes are costlier when the size
the Structure is small. of the class is small.

Allocation and de-allocation of Allocation and de-allocation of


Structs are costlier as compared to Classes are cheaper as compared
classes when the size of a struct is to Structs when the size of the
large. class is large.
Structs can contain limited kind of Classes can contain all kind of
entities like variables, structs, etc, entities like variables, functions,
and hence is used to create smaller constructors, structs, etc, and
codes. hence is used to create large
codes efficiently.
Structures are not allowed to contain Classes can contain any kind of
parameterless constructors or constructors or destructors.
destructors, but only parameterized
constructors and static constructors.

An instance of a struct can be To create an instance of a class, a


created by using the new keyword, as new keyword is used.
well as without using a new keyword.
A Struct cannot implement A Class can implement Inheritance
Inheritance and hence cannot inherit and can inherit from another
another struct or class. class.

The attributes of a struct cannot be The attributes of a class can be


specified as protected. specified as protected.

A struct can neither have a virtual A class can have virtual methods
method nor an abstract method. as well as abstract methods.

24. What is the difference between dispose() and finalize() methods in


C#?
Both dispose() and finalize() methods are used for unallocating and freeing up
resources but:
● dispose() method is called explicitly by the user, whereas finalize() method is
called the system’s garbage collector at the end of execution.
● dispose() method is defined in the IDisposable interface, whereas the
finalize() method is defined in the Object class.
● dispose() method is a part of the developer’s code, whereas finalize() method
is a system-defined default method and not a part of the developer’s code.

BASIS FOR
DISPOSE( ) FINALIZE( )
COMPARISON

Definition dispose() method is finalize() method is defined


defined in IDisposable in java.lang.object class.
interface.

Syntax public void protected void


dispose( ){ finalize( ){
// Dispose code // finalization code
here here
} }

Invoked dispose() method is finalize() method is invoked


invoked by the user. by the garbage collector.
Purpose dispose() method is used finalize() method is used to
to free unmanaged free the unmanaged
resources upon invoking. resources when invoked by
the garbage collector.

Implementation dispose() method is Unlike dispose(), the


implemented whenever finalize() method is
there is a close( ) implemented for freeing up
method. unmanaged resources.

Access Specifier dispose() method is finalize() method is declared


declared as public. as private.

Performance dispose() method finalize() method is slower in


happens instantly and comparison with dispose()
hence is faster. method and can affect the
performance.

25. What is enum in C#?


Enum is a primitive data type in C# used to define numeric constants in the .NET
framework. Starting from 0, all the elements of the enum are given constant values,
each increasing by 1.
For example, if we declare an enum for days of the week, the first element (Sunday)
will get the value 0, the next element (Monday) will get the value 1, and so on till
Saturday, which will get the value 6.

enum daysOfWeek { Sunday, Monday, Tuesday, Wednesday,


Thursday, Friday, Saturday };

To access any element, all you need to do is just pass the value of the element
alongside enum’s variable, such as:

daysOfWeek[5]; // Will give the value Friday

26. What are Interlocked functions?


Shared variables in C# are not thread-safe. It means that any operation on a variable
can be corrupted due to multiple threads. To prevent these dirty reads, C# allows the
use of interlocked functions to change the value of shared variables in
multithreading code.

Interlocked functions only support int, long, double and float data types, as shown by
some of the examples below:

1) Add(ref int address1, int value): Interlocked function to add a value into an int
variable safely.

2) Increment(ref int address1): Interlocked function to increment value of an int


variable safely by 1.

3) Decrement(ref int address1): Interlocked function to decrement value of an int


variable safely by 1.
4) Exchange(ref int address1, int value): Interlocked function to replace the value of
an int variable safely.

5) CompareExchange(ref int address1, int newValue, int toBeValue): Interlocked


function to replace the value of an int variable safely only if the existing value is
equal to passed toBeValue.

27. What is AutoResetEvent and how is it different from


ManualResetEvent?
AutoResetEvent is used to unlock a single thread when multiple threads are in a
waiting blocked state, whereas ManualResetEvent is used to unlock multiple threads
at once during similar instances.

AutoResetEvent also calls the Reset() method by itself to unblock the thread under
consideration, whereas while using ManualResetEvent, the Reset() method has to be
called manually after the use of set() method.

28. What is Mutex and how is it different from other Synchronization


mechanisms?
MuTex refers to Mutual Exclusion and as the name suggests, Mutex works on the
mutual exclusion principle to lock out any other thread requesting for a resource
whose access is already given to some thread. Mutex acts as a flag mechanism that
prevents any second thread from accessing a resource, except for the thread which
is currently working on it.

Unlike other synchronization mechanisms in C#, such as Auto Reset Event which can
give the exclusive access of a resource to any thread that calls the set() method,
Mutex remembers the thread that gets the resource access, and only that same
thread can reset it, thereby giving the true mutual exclusion synchronization. If the
thread differs, a mutex exception is thrown.
30. What is the lock statement in C#?

During multi-threading, when a thread is inside a critical section, it must not be


removed or stopped until it is completed. To implement this feature, lock statements
are used in C# which prevents other threads from entering a locked code (currently
in the critical section), until the object is released.

31. What are sealed classes in C#?

If we want to prevent any class from being inherited, it can be done with the help of a
sealed keyword. So using a sealed keyword, a class denies the ability to create any
child entity of this class, thereby calling itself a sealed class. If by mistake, a child of
a sealed class is tried to be made, a compile-time error will occur.

: (Location of the symbol related to previous error)

Compilation failed: 1 error(s), 0 warnings

32. What is Serialization in C#?


When we want to store any object to a memory, a database, or a file, it needs a
special process known as Serialization.

Serialization is the process of converting an object into a different form to store it on


to a file, database, or memory. The purpose of Serialization is to transfer the object
and its state across the network and recreate it successfully when needed.

The reverse of Serialization is known as Deserialization.


There are many types of serialization in C#, such as:

● Binary serialization: To save the state of the object in binary format. This is
done using classes defined in the System.Runtime.Serialization namespace.
● Soap Serialization: To save the state of the object in binary format, with the
use of network-related communication.
● XML Serialization: To save the state of the object in XML format. This is done
using classes defined in the System.Xml.Serialization namespace.
● JSON Serialization: To save the state of the object in JSON format. This is
done using classes defined in the System.Text.Json namespace.
There are some third-party serialization formats as well that are supported in C#,
such as MessagePack (msgpack).

1. How is C# different from C?


You would always know C being the procedural language while C# is a more object-
oriented language. The biggest difference is that C# supports automatic garbage
collection by Common Language Runtime (CLR) while C does not. C# primarily
needs a .NET framework to execute while C is a platform-agnostic language.

2. What is Common Language Runtime (CLR)?


CLR handles program execution for various languages including C#. The architecture
of CLR handles memory management, garbage collection, security handling, and
looks like:
Architecture of CLR

3. What is garbage collection in C#?


Garbage collection is the process of freeing up memory that is captured by
unwanted objects. When you create a class object, automatically some memory
space is allocated to the object in the heap memory. Now, after you perform all the
actions on the object, the memory space occupied by the object becomes waste. It is
necessary to free up memory. Garbage collection happens in three cases:

● If the occupied memory by the objects exceeds the pre-set threshold value.
● If the garbage collection method is called
● If your system has low physical memory
4. What are the types of classes in C#?

Class is an entity that encapsulates all the properties of its objects and instances as
a single unit. C# has four types of such classes:

● Static class: Static class, defined by the keyword ‘static’ does not allow
inheritance. Therefore, you cannot create an object for a static class.
● Partial class: Partial class, defined by the keyword ‘partial’ allows its members
to partially divide or share source (.cs) files.
● Abstract class: Abstract classes are classes that cannot be instantiated
where you cannot create objects. Abstract classes work on the OOPS concept
of abstraction. Abstraction helps to extract essential details and hide the
unessential ones.
● Sealed class: Sealed classes are classes that cannot be inherited. Use the
keyword sealed to restrict access to users to inherit that class.

5. What is a managed and unmanaged code?


Managed code lets you run the code on a managed CLR runtime environment in the
.NET framework.

Managed code runs on the managed runtime environment than the operating system
itself.

Benefits: Provides various services like a garbage collector, exception handling, etc.

Unmanaged code is when the code doesn’t run on CLR, it is an unmanaged code that
works outside the .NET framework.

They don’t provide services of the high-level languages and therefore, run without
them. Such an example is C++.
6. What is the difference between an abstract class and an interface?
Let’s dig into the differences between an abstract class and an interface:

● Abstract classes are classes that cannot be instantiated ie. that cannot create
an object. The interface is like an abstract class because all the methods
inside the interface are abstract methods.
● Surprisingly, abstract classes can have both abstract and non-abstract
methods but all the methods of an interface are abstract methods.
● Since abstract classes can have both abstract and non-abstract methods, we
need to use the Abstract keyword to declare abstract methods. But in the
interface, there is no such need.
An abstract class has constructors while an interface encompasses none.

○ between an Array and ArrayList in C#?


○ 11.What is inheritance? Does C# support multiple inheritance?
● C# Advanced Interview Questions
○ 12.What is Boxing and Unboxing in C#?
○ 13.What are Properties in C#?
○ 14.What are partial classes in C#?
○ 15.What is the difference between late binding and early binding in C#?
○ 16.What are the Arrays in C#?
○ 17.What are Indexers in C#?
○ 18.Difference between the Equality Operator (==) and Equals() Method
in C#?
○ 19.What are the different ways in which a method can be Overloaded in
C#?
○ 20.What is Reflection in C#?
○ 21.What is the difference between constant and readonly in C#?
○ 22.What is the difference between String and StringBuilder in C#?
● C# Coding Problems
○ 23.Write a program in C# Sharp to reverse a string?
○ 24.Write a program in C# Sharp to reverse the order of the given
words?
○ 25.Write a program in C# Sharp to find if a given string is palindrome or
not?
○ 26.Write a C# program to find the substring from a given string.
○ 27.Write a C# program to find if a positive integer is prime or not?
● C# MCQ
C sharp is an object-oriented programming language developed by Microsoft. C# is
used with the .NET framework for creating websites, applications, and games. C#
has a varied reason for being popular:

Comparatively easier: Starting with C# is termed comparatively easier than other


programming languages

Wider use of development: Using C#, you are prone to create web applications or
gaming apps. C# has some fantastic features like automatic garbage collection,
interfaces, etc. which help build better applications.

Larger target audience: Collaboration with Microsoft provides an edge to the


applications created using C# since it would have a wider target audience.

Since C# is such a widely-used programming language, a plethora of big and small


organizations base their products using it. So, prepare yourself with basic and
advanced level C# questions to ace the interviews.

Let’s look at 50 much asked and a comprehensive set of questions and answers on
C#.

C# Basic Interview Questions

1. How is C# different from C?


You would always know C being the procedural language while C# is a more object-
oriented language. The biggest difference is that C# supports automatic garbage
collection by Common Language Runtime (CLR) while C does not. C# primarily
needs a .NET framework to execute while C is a platform-agnostic language.

2. What is Common Language Runtime (CLR)?


CLR handles program execution for various languages including C#. The architecture
of CLR handles memory management, garbage collection, security handling, and
looks like:

Architecture of CLR

3. What is garbage collection in C#?


Garbage collection is the process of freeing up memory that is captured by
unwanted objects. When you create a class object, automatically some memory
space is allocated to the object in the heap memory. Now, after you perform all the
actions on the object, the memory space occupied by the object becomes waste. It is
necessary to free up memory. Garbage collection happens in three cases:

● If the occupied memory by the objects exceeds the pre-set threshold value.
● If the garbage collection method is called
● If your system has low physical memory
You can download a PDF version of C Sharp Interview Questions.

Download PDF

4. What are the types of classes in C#?


Class is an entity that encapsulates all the properties of its objects and instances as
a single unit. C# has four types of such classes:

● Static class: Static class, defined by the keyword ‘static’ does not allow
inheritance. Therefore, you cannot create an object for a static class.
Sample code:

static class classname

{
//static data members

//static methods

● Partial class: Partial class, defined by the keyword ‘partial’ allows its members
to partially divide or share source (.cs) files.
● Abstract class: Abstract classes are classes that cannot be instantiated
where you cannot create objects. Abstract classes work on the OOPS concept
of abstraction. Abstraction helps to extract essential details and hide the
unessential ones.
● Sealed class: Sealed classes are classes that cannot be inherited. Use the
keyword sealed to restrict access to users to inherit that class.

sealed class InterviewBit

// data members

// methods

5. What is a managed and unmanaged code?


Managed code lets you run the code on a managed CLR runtime environment in the
.NET framework.

Managed code runs on the managed runtime environment than the operating system
itself.

Benefits: Provides various services like a garbage collector, exception handling, etc.

Unmanaged code is when the code doesn’t run on CLR, it is an unmanaged code that
works outside the .NET framework.

They don’t provide services of the high-level languages and therefore, run without
them. Such an example is C++.

6. What is the difference between an abstract class and an interface?


Let’s dig into the differences between an abstract class and an interface:

● Abstract classes are classes that cannot be instantiated ie. that cannot create
an object. The interface is like an abstract class because all the methods
inside the interface are abstract methods.
● Surprisingly, abstract classes can have both abstract and non-abstract
methods but all the methods of an interface are abstract methods.
● Since abstract classes can have both abstract and non-abstract methods, we
need to use the Abstract keyword to declare abstract methods. But in the
interface, there is no such need.
An abstract class has constructors while an interface encompasses none.

Ex.
Abstract class:

public abstract class Shape{

public abstract void draw();

Interface:

public interface Paintable{

void paint();

7. What are the differences between ref and out keywords?


C# ref keywords pass arguments by reference and not value. To use the ‘ref’
keyword, you need to explicitly mention ‘ref’.

C# out keywords pass arguments within methods and functions.

‘out’ keyword is used to pass arguments in a method as a reference to return


multiple values. Although it is the same as the ref keyword, the ref keyword needs to
be initialised before it is passed. Here, The out and ref keywords are useful when we
want to return a value in the same variables that are passed as an argument.

8. What are extension methods in C#?

Extension methods help to add new methods to the existing ones. The methods that
are added are static. At times, when you want to add methods to an existing class
but don’t perceive the right to modify that class or don’t hold the rights, you can
create a new static class containing the new methods. Once the extended methods
are declared, bind this class with the existing one and see the methods will be added
to the existing one.

. What are Generics in C#?


In C# collections, defining any kind of object is termed okay which compromises
C#’s basic rule of type-safety. Therefore, generics were included to type-safe the
code by allowing re-use of the data processing algorithms. Generics in C# mean not
linked to any specific data type. Generics reduce the load of using boxing, unboxing,
and typecasting objects. Generics are always defined inside angular brackets <>. To
create a generic class, this syntax is used:

GenericList<float> list1 = new GenericList<float>();

GenericList<Features> list2 = new GenericList<Features>();

GenericList<Struct> list3 = new GenericList<Struct>();

Here, GenericList<float> is a generic class. In each of these instances of


GenericList<T>, every occurrence of T in the class is substituted at run time with the
type argument. By substituting the T, we have created three different type-safe using
the same class.

10. What is the difference between an Array and ArrayList in C#?


An array is a collection of similar variables clubbed together under one common
name. While ArrayList is a collection of objects that can be indexed individually. With
ArrayList you can access a number of features like dynamic memory allocation,
adding, searching, and sorting items in the ArrayList.
● When declaring an array the size of the items is fixed therefore, the memory
allocation is fixed. But with ArrayList, it can be increased or decreased
dynamically.
● Array belongs to system.array namespace while ArrayList belongs to the
system.collection namespace.
● All items in an array are of the same datatype while all the items in an
ArrayList can be of the same or different data types.
● While arrays cannot accept null, ArrayList can accept null values.

What is inheritance? Does C# support multiple inheritance?


Inheritance means acquiring some of the properties from a master class.

Multiple Inheritance in C#
Here, class C can inherit properties from Class A and Class B. Here is an example of
inheritance:

// C# program to illustrate

// multiple class inheritance

using System;

using System.Collections;

// Parent class 1

class Scaler {

// Providing the implementation

// of features() method

public void features()

// Creating ArrayList
ArrayList My_features= new ArrayList();

// Adding elements in the

// My_features ArrayList

My_features.Add("Abstraction");

My_features.Add("Encapsulation");

My_features.Add("Inheritance");

Console.WriteLine("Features provided by OOPS:");

foreach(var elements in My_features)

Console.WriteLine(elements);

}
// Parent class 2

class Scaler2 :Scaler{

// Providing the implementation

// of courses() method

public void languages()

// Creating ArrayList

ArrayList My_features = new ArrayList();

// Adding elements in the

// My_features ArrayList

My_features.Add("C++");

My_features.Add("C#");

My_features.Add("JScript");
Console.WriteLine("\nLanguages that use OOPS
concepts:");

foreach(var elements in My_features)

Console.WriteLine(elements);

// Child class

class ScalertoScaler : Scaler2 {

public class Scaler1 {


// Main method

static public void Main()

// Creating object of ScalertoScaler class

ScalertoScaler obj = new ScalertoScaler();

obj.features();

obj.languages();

Also, C# doesn’t support multiple inheritances.

Instead, you can use interfaces to inherit the properties using the class name in the
signature.

12. What is Boxing and Unboxing in C#?


The two functions are used for typecasting the data types:
Boxing: Boxing converts value type (int, char, etc.) to reference type (object) which is
an implicit conversion process using object value.

Example:

int num = 23; // 23 will assigned to num

Object Obj = num; // Boxing

Unboxing: Unboxing converts reference type (object) to value type (int, char, etc.)
using an explicit conversion process.

Example:

int num = 23; // value type is int and assigned value


23

Object Obj = num; // Boxing

int i = (int)Obj; // Unboxing

13. What are Properties in C#?


Properties in C# are public members of a class where they provide the ability to
access private members of a class. The basic principle of encapsulation lets you
hide some sensitive properties from the users by making the variables private. The
private members are not accessible otherwise in a class. Therefore, by using
properties in C# you can easily access the private members and set their values.
The values can be easily assigned using get and set methods, also known as
accessors. While the get method extracts the value, the set method assigns the
value to the variables.

14. What are partial classes in C#?


Partial classes implement the functionality of a single class into multiple files. These
multiple files are combined into one during compile time. The partial class can be
created using the partial keyword.

public partial Clas_name

// code

You can easily split the functionalities of methods, interfaces, or structures into
multiple files. You can even add nested partial classes.

15. What is the difference between late binding and early binding in C#?
Late binding and early binding are examples of one of the primary concepts of OOPS:
Polymorphism.

For ex: one function calculateBill() will calculate bills of premium customers, basic
customers, and semi-premium customers based on their policies differently. The
calculation for all the customer objects is done differently using the same function
which is called polymorphism.
When an object is assigned to an object variable in C#, the .NET framework performs
the binding.

When the binding function happens at compile-time, it is called early binding. It


investigates and checks the methods and properties of the static objects. With early
binding, the number of run-time errors decreases substantially and it executes pretty
quickly.

But when the binding happens at runtime, it is called late binding. Late binding
happens when the objects are dynamic (decided based on the data they hold) at run-
time. It is slower as it looks through during run-time.

16. What are the Arrays in C#?


When a group of similar elements is clubbed together under one name, they are
called arrays.

For ex. An array of tea Atea[4]: [green tea, chamomile tea, black tea, lemon tea]. The
length of the array defines how many elements are present in the array.

In C#, the memory allocations for the elements of the array happen dynamically.
This is how values are stored in an array sequentially.
Arrays in C#

A few pointers for arrays in C#:

● The memory allocation is DYNAMIC.


● Arrays in C# are treated as objects.
● The length of the array is easy to find by detecting the number of members in
the array.
● The members in the array are ordered and begin with the index value=0.
● The array types are reference types derived from the base array type.
Syntax: < Data Type > [ ] < Name_Array >

17. What are Indexers in C#?


Indexers are called smart arrays that allow access to a member variable. Indexers
allow member variables using the features of an array. They are created using the
Indexer keyword. Indexers are not static members.

For ex. Here the indexer is defined the same way.

<return type> this[<parameter type> index]


{

get{

// return the value from the specified index of an


internal collection

set{

// set values at the specified index in an internal


collection

18. Difference between the Equality Operator (==) and Equals() Method
in C#?
Although both are used to compare two objects by value, still they both are used
differently.

For ex.:

int x = 10;

int y = 10;

Console.WriteLine( x == y);
Console.WriteLine(x.Equals(y));

Output:

True

True

Equality operator (==) is a reference type which means that if equality operator is
used, it will return true only if both the references point to the same object.

Equals() method: Equals method is used to compare the values carried by the
objects. int x=10, int y=10. If x==y is compared then, the values carried by x and y are
compared which is equal and therefore they return true.

Equality operator: Compares by reference

Equals(): Compares by value

19. What are the different ways in which a method can be Overloaded in
C#?
Overloading means when a method has the same name but carries different values
to use in a different context. Only the main() method cannot be overloaded.

In order to overload methods in C#,


● Change the number of parameters in a method, or
● Change the order of parameters in a method, or
● Use different data types for parameters
In these ways, you can overload a method multiple times.
For ex.

public class Area {

public double area(double x) {

double area = x * x;

return area;

public double area(double a, double b) {

double area = a * b;

return area;

Here, the method Area is used twice. In the first declaration, one argument is used
while in the second one, there were two arguments are used. Using different
parameters in the same method, we were able to overload the method area().

20. What is Reflection in C#?


Reflection in C# extracts metadata from the datatypes during runtime.

To add reflection in the .NET framework, simply use System.Refelction namespace


in your program to retrieve the type which can be anything from:

● Assembly
● Module
● Enum
● MethodInfo
● ConstructorInfo
● MemberInfo
● ParameterInfo
● Type
● FieldInfo
● EventInfo
● PropertyInfo

21. What is the difference between constant and readonly in C#?


A const keyword in C# is used to declare a constant field throughout the program.
That means once a variable has been declared const, its value cannot be changed
throughout the program.

In C#, a constant is a number, string, null reference, or boolean values.

For ex:
class IB {

// Constant fields

public const int xvar = 20;

public const string str = "InterviewBit";

// Main method

static public void Main()

// Display the value of Constant fields

Console.WriteLine("The value of xvar: {0}", xvar);

Console.WriteLine("The value of str: {0}", str);

Output:
The value of xvar is 20.

The value of string is Interview Bit

On the other hand, with readonly keyword, you can assign the variable only when it is
declared or in a constructor of the same class in which it is declared.

Ex:

public readonly int xvar1;

public readonly int yvar2;

// Values of the readonly

// variables are assigned

// Using constructor

public IB(int b, int c)

xvar1 = b;

yvar2 = c;
Console.WriteLine("The value of xvar1 {0}, "+

"and yvar2 {1}", xvar1, yvar2);

// Main method

static public void Main()

IB obj1 = new IB(50, 60);

Output:

The value of xvar1 is 50, and yvar2 is 60

Constants are static by default while readonly should have a value assigned when
the constructor is declared.
Constants can be declared within functions while readonly modifiers can be used
with reference types.

22. What is the difference between String and StringBuilder in C#?


The major difference between String and StringBuilder is that String objects are
immutable while StringBuilder creates a mutable string of characters. StringBuilder
will make the changes to the existing object rather than creating a new object.

StringBuilder simplifies the entire process of making changes to the existing string
object. Since the String class is immutable, it is costlier to create a new object every
time we need to make a change. So, the StringBuilder class comes into picture which
can be evoked using the System.Text namespace.

In case, a string object will not change throughout the entire program, then use String
class or else StringBuilder.

For ex:

string s = string.Empty;

for (i = 0; i < 1000; i++)

s += i.ToString() + " ";

Here, you’ll need to create 2001 objects out of which 2000 will be of no use.

The same can be applied using StringBuilder:


StringBuilder sb = new StringBuilder();

for (i = 0; i < 1000; i++)

sb.Append(i); sb.Append(' ');

You might also like