C# Interview Question
C# Interview Question
Debuting back in 2000, C# has succeeded in becoming one of the leading programming
languages. As a multi-paradigm programming language, C# also has some features
of functional programming that takes its usefulness and versatility to a step further.
Static Class: It is the type of class that cannot be instantiated, in other words,
we cannot create an object of that class using the new keyword and the class
members can be called directly using their class name.
Abstract Class: Abstract classes are declared using the abstract keyword.
Objects cannot be created for abstract classes. If you want to use it then it must
be inherited in a subclass. You can easily define abstract or non-abstract
methods within an Abstract class. The methods inside the abstract class can
either have an implementation or no implementation.
Partial Class: It is a type of class that allows dividing their properties, methods,
and events into multiple source files, and at compile time these files are
combined into a single class.
Sealed Class: One cannot inherit a sealed class from another class and
restricts the class properties. Any access modifiers cannot be applied to the
sealed class.
Question: Explain different access modifiers in C#?
Answer: These are the keywords that help to define the accessibility of class, member,
and data type in the program. These keywords are used to restrict the use of some data
manipulation done by other classes. There are 4 types of access modifiers- public,
private, protected, and internal. These modifiers define 6 other accessibility levels when
working together- public, protected, internal, protected internal, private, and private
protected.
Below is the access chart of the modifiers.
PROTECTE PRIVATE
PUBLI PROTECTE INTERNA PRIVAT
D PROTECTE
C D L E
INTERNAL D
Complete
Yes No No No No No
program
Derived
types
within the Yes Yes No Yes No Yes
current
assembly
Using
Yes Yes Yes Yes Yes Yes
class
Current
Yes No Yes Yes No No
assembly
Derived
Yes Yes No Yes No No
data types
Encapsulation: defines the binding together code and the data and keeps it safe
from any manipulation done by other programs and classes. It is a container that
prevents code and data from being accessed by another program that is defined
outside the container.
Abstraction: this concept of object-oriented protects everything other than the
relevant data about any created object in order to increase efficiency and security
within the program.
Inheritance: Inheritance is applied in such a way where one object uses the
properties of another object.
Polymorphism: is a feature that allows one interface to act as a base class for
other classes. This concept is often expressed as a "single interface but multiple
actions".
First, compile the source code in the managed code compatible with the C#
compiler.
Second, combine the above newly created code into assemblies.
Third, load the CLR.
Last, execute the assembly by CLR to generate the output.
Break Continue
You can use break statements in both switch and You can use continue statements only in the
loop (for, while, and do-while ) statements. loop (for, while, do) statements.
Question: How you can explain the use of ‘using’ statements in C# in detail.
Answer: The using statement is used to control the usage of one or more resources
that are being used within the program. The resources are continuously consumed and
released. The main function of this statement is to manage unused resources and
release them automatically. Once the object is created which is using the resource and
when you are done you make sure that the object’s dispose method is called to release
the resources used by that object, this is where using statements works well.
For example:
try: a raised exception finds a particular block of code to get handled. There is no
limit on the number of catch blocks that you will use in your program to handle
different types of exception raised.
catch: you can handle the raised exception within this catch block. You can
mention the steps that you want to do to solve the error or you can ignore the
error by suppressing it by the code.
Finally: irrespective of the error, if you still want some set of instructions to get
displayed then you can use those statements within the finally block and it will
display it on the screen.
throw: you can throw an exception using the throw statement. It will display the
type of error you are getting.
Syntax:
try {
//exception handling starts with try block
} catch( ExceptionName ea1 ) {
// errors are handled within the catch block
} catch( ExceptionName e2 ) {
// more catch block
} catch( ExceptionName eN ) {
// more catch block to handle multiple exception raised
} finally {
// last block of the exception handling
}
~class_name()
{
//code
}
For example:
public class Methodoveloading
{
public int sum(int a, int b) //two int type Parameters method
{
return a + b;
}
public int sum(int a, int b,int c) //three int type Parameters with same method
same as above
{
return a + b+c;
}
public float sum(float a, float b,float c,float d) //four float type Parameters
with same method same as above two method
{
return a + b+c+d;
}
}
Question: What are the control statements that are used in C#?
Answer: You can control the flow of your set of instructions by using control statements
and we majorly focus on if statements. There are a few types of if statements that we
consider for making situations to control the flow of execution within a program.
These are the 4 types of if statements:
If
If-else
Nested if
If-else-if
If(any condition)
{
//code to be executed if the condition returns true
}
If-else statement checks for the given condition, if the condition turns out to be false
then the flow will transfer to the else statement and it will execute the else instructions.
In case, the if condition turns out to be true then the if instructions will get executed.
Syntax:
If(condition)
{
//code to be run if the condition is true
}
Else
{
//code to be run if the if-condition is false
}
Nested if statement checks for the condition, if the condition is true then it will check for
the inner if statement and keeps going on for the last if statement. If any of the
conditions are true then it will execute the particular if instructions and stops the if loop
there.
Syntax:
If (condition to be checked)
{
//code
If(condition 2)
{
//code for if-statement 2
}
}
If else-if checks for the given condition, if the condition is not true then the control will go
to the next else condition, if that condition is not true it will keep on checking for next
else conditions. If any of the conditions did not pass then the last else instructions will
get executed.
Syntax:
If(condition 1 to be checked)
{
//code for condition 1
}
Else (condition 2 to be checked)
{
//code for condition 2
}
Else
{
//code will run if no other condition is true
}
Question: Explain the concept of boxing and unboxing of the value type and
object type in C#.
Answer:
Boxing- is a process of converting a value type to an object type where value type is
placed on the stack memory, and the object type is placed in the heap memory. This
conversion is an implicit conversion and you can directly assign any value to an object,
and C# will handle the rest of the conversion on its own.
Example:
Question: How can you check if a number is an Armstrong number or not with
C#?
Answer:
using System;
public class ArmstrongDemo
{
public static void Main(string[] args)
{
int n,b,sum=0,num;
Console.Write("Enter the Number= ");
n= int.Parse(Console.ReadLine());
num=n;
while(n>0)
{
b=n%10;
sum=sum+(b*b*b);
n=n/10;
}
if(num==sum)
Console.Write("Armstrong Number.");
else
Console.Write("Not Armstrong Number.");
}
}
Output:
Enter the Number= 371
Armstrong Number.
namespace MulticastDelegate
{
public class Rectangle
{
public void Area(double Width, double Height)
{
Console.WriteLine(@"Area is {0}", (Width * Height));
}
public void Perimeter(double Width, double Height)
{
Console.WriteLine(@"Perimeter is {0}", (2 * (Width + Height)));
}
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
rect.Area(23.45, 67.89);
rect.Perimeter(23.45, 67.89);
Console.ReadKey();
}
}
}
Here, we created an instance of the Rectangle class and then called the two different
methods. Now a single delegate will invoke these two methods Area and Perimeter.
These defined methods are having the same signature as the defined delegates that
hold the reference to these methods.
Creating multicast delegate:
namespace MulticastDelegateDemo
{
public delegate void RectangleDelete(double Width, double Height);
public class Rectangle
{
public void Area(double Width, double Height)
{
Console.WriteLine(@"Area is {0}", (Width * Height));
}
public void Perimeter(double Width, double Height)
{
Console.WriteLine(@"Perimeter is {0}", (2 * (Width + Height)));
}
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
RectangleDelete rectDelegate = new RectangleDelete(rect.Area);
rectDelegate += rect.Perimeter;
rectDelegate(23.45, 67.89);
Console.WriteLine();
rectDelegate.Invoke(13.45, 76.89);
Console.WriteLine();
//Removing a method from delegate object
rectDelegate -= rect.Perimeter;
rectDelegate.Invoke(13.45, 76.89);
Console.ReadKey();
}
}
}
Question: How you can implement nullable<> types in C#? explain with the
syntax of Nullable type.
Answer: In C#, you cannot put a null value directly into any variable and the compiler
does not support it. So, the revised version C# 2.0 provides you with a special feature
that will assign a null value to a variable that is called as the Nullable type. You cannot
make the nullable types to work with value types. Nullable value can only work with the
reference types as it already has a null value. System.Nullable<T> structure creates the
instance nullable type, where T defines the data type. This T contains a non-nullable
value type that can be any data type you want.
Syntax
Nullable<data_type> variable_name=null;
OR
Datatype? variable_name=null;
There is no possibility that you can access the value of the nullable value type directly
with assigning the value. For getting its original assigned value you have to use the
method GetValueOrDefault(). If the value is null then it will provide zero as it is its
default value.
Question: What do you mean by value types and reference types in C#?
Answer:
Value type:
The memory allocated for the value type content or assigned value is stored on the
stack. When we create any variable, space is allocated to that variable and then a value
can be assigned to that variable. Also if we want to copy the value of that variable to
another variable, its value gets copied and that creates two different variables.
Reference Type:
It holds the reference to the address of the object but not the object directly. Reference
types represent the address of the variable and assigning a reference variable to
another does not copy the data but it creates a second copy of the reference which
represents the same location on the heap as the original value. Reference values are
stored on the heap and when the reference variable is no longer required it gets marked
for garbage collection.
Question: What are various types of comments in C#, explain with example?
Answer: C# supports three types of comments-
1. Single line comment
Syntax: //single line
2. Multiple line comment
Syntax: /* multiple lines
*/
3. XML comment
Syntax: /// set error
FileStream This stream read from and write to any location within a file
// Interface
Interface IAnimal {
void Sound(); // interface method (without body)
}
class Pig : IAnimal // Pig class "implements" the IAnimal interface
{
public void Sound()
{
Console.WriteLine("The pig says: wee wee"); // The body of Sound() is provided her
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}}
Question: What do you mean by user control and custom control in C#?
Answer: User controls are very easy to create and are very much the same as the ASP
control files. You cannot place a user control on the toolbox and cannot even drag-drop
it. They have unique design and individual code behind these controls. Ascx is the file
extension for user control.
You can create custom code as the compiled code and can be added to the toolbox.
You can include these controls to the web forms easily. Custom controls can be added
to multiple applications efficiently. If you want to add a private custom control then you
can copy it to dll and then to the bin directory of your web application and use its
reference there.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Application
{
class DemoProgram
{
static void Main(string[] args)
{
Queue qs = new Queue();
qs.Enqueue(1);
qs.Enqueue(2);
qs.Enqueue(3);
foreach (Object ob in qs)
{
Console.WriteLine(ob);
}
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("Total number of elements in the Queue " + qs.Count);
Console.WriteLine("Does the Queue contain " + qs.Contains(3));
Console.ReadKey();
}
}
}
using System;
public class PalindromeNum
{
public static void Main(string[] args)
{
int n,r,num=0,Dem;
Console.Write("Enter the Number: ");
n = int.Parse(Console.ReadLine());
dem=n;
while(n>0)
{
r=n%10;
num=(num*10)+r;
n=n/10;
}
if(dem==num)
Console.Write("Number is Palindrome.");
else
Console.Write("Number is not Palindrome");
}
}
Question: What are I/O classes in C#? Define some of the most commonly used
ones.
Answer: The System.IO namespace in C# consists of several classes used for
performing various file operations, such as creation, deletion, closing, and opening.
Some of the most frequently used I/O classes in C# are:
if(System.Text.RegularExpressions.Regex.IsMatch(s,“C#”))
Console.WriteLine(“Match found”);
System.Delegate namespace.
After declaring a delegate, the object must be created of the delegate using the new
keyword, such as:
The Delegate offers a kind of encapsulation to the reference method, which gets
internally called with the calling of the delegate. In the following example, we have a
delegate myDel that takes an integer value as a parameter: public delegate int
myDel(int number); public class Program { public int AddNumbers(int a) { Int Sum = a +
10; return Sum; } public void Start() { myDel DelgateExample = AddNumbers; } }
The system contains all classes and methods that manage the information of all the
loaded types and methods. Reflection namespace. Implementation of reflection is in 2
steps:
Question: Name some of the most common places to look for a Deadlock in C#.
Answer: For recognizing deadlocks, one should look for threads that get stuck on one
of the following:
Binary Serialization – Faster and demands less space; it converts any code into
its binary form. Serialize and restore public and non-public properties.
SOAP – It produces a complete SOAP compliant envelope that is usable by any
system capable of understanding SOAP. The classes about this type of
serialization reside in System.Runtime.Serialization.
XML Serialization – Serializes all the public properties to the XML document. In
addition to being easy to read, the XML document manipulated in several
formats. The classes in this type of serialization reside in
System.sml.Serialization.
Note: Retrieving the C# code back from the binary form is known as Deserialization.
Question: What can you tell us about the XSD file in C#?
Answer: XSD denotes XML Schema Definition. The XML file can have any attributes,
elements, and tags if there is no XSD file associated with it. The XSD file gives a
structure for the XML file, meaning that it determines what, and also the order of, the
elements and properties that should be there in the XML file. Note: - During serialization
of C# code, the classes are converted to XSD compliant format by the Xsd.exe tool.
get {
set {
Question: Give a detailed explanation of the differences between ref and out
keywords.
Answer: In any C# function, there can be three types of parameters, namely in, out and
ref. Although both out and ref are treated differently at the run time, they receive the
same treatment during the compile time. It is not possible to pass properties as an out
or ref parameter. Following are the differences between ref and out keywords:
namespace Singleton {
class Program {
Calculate.Instance.ValueOne = 10.5;
Calculate.Instance.ValueTwo = 5.5;
Console.WriteLine("\n----------------------\n");
Calculate.Instance.ValueTwo = 10.5;
Console.ReadLine();
private Calculate() {}
get {
if (instance == null) {
return instance;
get;
set;
get;
set;
A Singleton Design Pattern ensures that a class has one and only one instance and
provides a global point of access to the same. There are numerous ways of
implementing the Singleton Design Patterns in C#. Following are the typical
characteristics of a Singleton Pattern:
A public static means of getting the reference to the single instance created
A single constructor, private and parameter-less
A static variable holding a reference to the single instance created
The class is sealed