0% found this document useful (0 votes)
3 views31 pages

C Interview Questions and Answers Common C Questions

The document provides a comprehensive overview of key concepts and features in C#, including data types, managed and unmanaged code, exception handling, reflection, garbage collection, serialization, encapsulation, assembly, generics, and type conversion. It also outlines the differences between value types and reference types, explains exception handling mechanisms, and details the significance of attributes and assembly metadata. Additionally, the document highlights the evolution of C# through its versions and the introduction of new features such as generics and LINQ.

Uploaded by

bhupinder singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views31 pages

C Interview Questions and Answers Common C Questions

The document provides a comprehensive overview of key concepts and features in C#, including data types, managed and unmanaged code, exception handling, reflection, garbage collection, serialization, encapsulation, assembly, generics, and type conversion. It also outlines the differences between value types and reference types, explains exception handling mechanisms, and details the significance of attributes and assembly metadata. Additionally, the document highlights the evolution of C# through its versions and the introduction of new features such as generics and LINQ.

Uploaded by

bhupinder singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

About

Data types
What are the different data types in c#?
What are reference type and values types?
What is Nullable type?
Managed and Unmanaged code
What is managed and unmanaged code?
Value types
What is a value type?
What is Enum?
What is Struct ?
Reference types
What is a reference type?
Explain class?
Explain what is the use of delegate?
Features in different versions
Explain the new features added in different versions of C#?
Exception handling
Explain Exception handling in C#?
What is System.Exception?
Reflection
What are Attributes?
Garbage Collection
What is Garbage collection?
Serialization
What is Serialization?
What is the difference between Dispose and Finalize methods?
Encapsulation
Access modifiers?
Assembly
What is Assembly ?
What is ILDASM?
What is Assembly Version number?
What is strongly named assembly?
How do you sign an Assembly with a Strong Name?
The Assembly Manifest?
The Global Assembly Cache?
Assembly Info.cs?
Generics
What are Generics?
Type conversion
Casting in C#?
What are the “as” and “is” operators in C#?
Loops
What is the difference between “continue” and “break” statements in C#?
Difference between string and StringBuilder class in C#?
Differences between abstract class and interface
Differences between enum and struct
Difference between readonly and const
Differences between IEnumerable and IQueryable
Difference between Array and ArrayList
What is extension method?
Classes
What is a sealed class in c#?
What are partial classes?
Collections
How do you sort elements in an array?
What is IComparer interface?
LINQ
What is LINQ?
What is LINQ Data Provider?
What is LINQ to Objects?
What is LINQ to SQL?
What is DataContext?
What is LINQ to XML?
What is IQueryable<T> interface?
About
These are some of the important questions which are commonly asked in C#
interviews.These will also help to revise the basic concepts of the language.For other
information related to C# and .NET you can refer codecompiled.It has resources
related to .NET.
Data types
What are the different data types in c#?
Data type allows the programmer to use different types of data in a application.There
are different data types for different data used in a application.Data types defines the
range of values a variable of the data type can use and the different operations which
can be performed on the value.
Every variable in C# has a specific data type. This is because C# is a strongly typed
language.C# has many predefined data types.There are main two types in C# value
type and reference type.Every data type belongs to one of these.For example integer
is a value type.
If required we can create custom data types such as a class and structure.Some of the
predefined data types are:
Numeric
Integer Float
Data Type Description range Data description range
Type
byte Unsigned integer 8 bit Float Single 32-bit
floating-
point
values.
sbyte Signed integer 8 bit Double Double 64-bit
floating-
point values
int Signed integer 32 bit Char Unicode 16-bit
character.
uint Unsigned integer 32 bit Decimal Decimal 128-bit
monetary
values
short Signed integer 16 bit

ushort Unsigned integer 16 bit

long Signed integer 64 bit

ulong Unsigned integer 64 bit


Other Data Types
Data Type Description Data Type Description
object All data types DateTime DateTime
inherit from object values
type
string Represents bool Only
sequence of zero True/False
or more Unicode values
characters.
What are reference type and values types?
The data types in .NET are either value types or reference types.The difference
between the two is where the actual value is stored.In the case of reference type value
is stored on the heap.Pointer to this actual value is stored on the stack.
In the case of value type value is in the memory and there is no pointer to this
value.The variable directly points to the value on the stack.
You initialize a variable of reference type by using a new operator:
For example if you have declared a class then you can create its object as:
Employee emp =new Employee();

What is Nullable type?


By definition of value types we cannot assign null value to any variable of value
type.Only reference types can be assigned null values.
"Nullable types allows to assign Null values to value types."
You can declare a variable of a nullable type as:
System.Nullable<T> variable = null;
Or
T? variable = null;
T is the data type in the above example.So if you want to declare a nullable value
type based on type T then you can declare as:
System.Nullable<int> counter = null;
Or
int? counter = null;
above we are declaring a Nullable integer type.
Managed and Unmanaged code
What is managed and unmanaged code?
Code which is developed in any .NET compatible language and is executed by CLR
is called managed code.Code which is not executed by CLR is called unmanaged
code.You need to install .NET framework on your machine to execute managed
code,since CLR is part of .NET framework.The managed code you write in any .NET
language such as C# is converted into MSIL.At runtime MSIL is converted to native
code by JIT compiler.
CLR provides the services to the manged code such as:
● Memory management
● Security
● Conversion of IL to native code
● Type SafetyValue types

Value types
What is a value type?
Types in C# can be broadly categorized into:
● reference types contains the value
● value types contains the reference of memory address instead of value
What is Enum?
Enum is a set of named constants.The first enumerator has the value 0 and every next
enumerator's value is incremented by 1.Enum can be of any integer type such as
int,float,byte.Enum (also called enumertion) is declared using the enum keyword.

For example you can declare an enum called Employee type as:
enum EmployeeType {
FullTime;
Contractor;
Intern;
};
In this enum the enumerator FullTime has the value 0.The values of Contractor and
Intern enumerators are 1 and 2 respectively.
What is Struct ?
The struct is a datatype like class.Struct is lightweight compared to class.It is used
when we don’t want to use reference type such as class because of performance
overhead.
We declare struct using the struct keyword as:
public struct Sample
{
public int a,b;
public Sample(int x, int y)
{
a = x;
b= y;
}
}
Reference types
What is a reference type?
Reference type variables contains the reference instead of actual data.So two different
reference variables can point to the same memory location.This could have other
effects such as the value of the reference variable being modified by a different
variable.
Some examples of reference types are:
● Class
● Interface
● Delegate
● Array
Explain class?
A class allows to create custom types by grouping together variables and
methods.Class is defined by using the class keyword.
Following is a sample class having some of the class members:
public class Sample
{
public string field1 = string.Empty;
//constructor
public Sample()
{
}
//method
public void Method1(int param1)
{
}
//variable
private int _prop1;
//property
public int Prop1
{
get { return _prop1;; }
set { _prop1;= value; }
}
}

Explain what is the use of delegate?


A delegate is a function pointer.A delegate object refers to a function.The advantage
is that the method to call can be deferred until runtime.
A delegate object is declared using the delegate keyword.For example you can
declare a delegate called FirstDelegate as:
public delegate void FirstDelegate();
The above delegate can point to any method which is parameter-less and doesn’t
return any value.If you have a method declared as:
public static void FirstMethod()
{
}
Then you can assign reference of the above method to FirstMethod as:
FirstDelegate delObj=new FirstDelegate(FirstMethod);
Now you can call the FirstMethod method using delegate as:
delObj();
What is a constructor?
A constructor is a method of a class which is automatically called when an object of a
class is created.A distinguishing point about constructor is that it has the same name
as the class.For example if you have a class called sample then you will define a
constructor in the class by defining a method with the name Sample:
public class Sample
{
public string field1 = string.Empty;
//constructor
public Sample()
{
}
}
The constructor of the Sample class will be automatically called when you create an
object of the Sample class.You can try this yourself by adding WriteLine() statement
in the above Sample() constructor.
Features in different versions
Explain the new features added in different versions of C#?
There has been many releases of C# since the Original version 1.0.Current version is
C# 7.0.Following are some of the features which have been added with the new
releases.
C# was introduced with .NET Framework 1.0 and the current version of C# is 6.0.

Version 2.0 Version 3.0 Version 4.0 Version 5.0 version 6.0 Version
7.0
Generics Implicitly typed Dynamic Async Expression out
local variables binding (late features Bodied variables
binding) Methods

Anonymous Object and Named and Caller Auto- Tuples


methods collection optional information property
initializers arguments initializer

Partial Auto-Implemented Exception Discards


types properties Filter

Nullable Anonymous types String Pattern


types Interpolation Matching

Iterators Extension methods Local


functions

Lambda
expressions

Partial Methods
Exception handling
Explain Exception handling in C#?
Error is any undesirable behaviour in the program.Exceptions are runtime errors.To
handle the runtime errors or exceptions exception handling is used in C#.C# uses the
following keywords for Exception handling:
try defines a try block.Contains logic which could throw exception.
catch defines a catch block.Contains logic which handles the exception
thrown by the catch block
finally defines a finally block.This block always executes whether the
exception is thrown or not.You can define logic which you always want to
execute in this block.
throw keyword used to throw a new exception that is handled by
try..catch..finally blocks.
What is System.Exception?
When a runtime error occurs an exception is thrown. System.Exception is the base
class for all exceptions.Exception contains information about the error.Some of the
useful properties defined by the System.Exception class are:
StackTrace Information about the call stack.
InnerException Exception that caused the current exception.
Message Describes exception.
HelpLink Link to the information about exception.
HResult Numerical value for the exception.
Source Application that caused the exception.
TargetSite Method which threw the exception.
Data User-defined information about the exception.
Reflection
What are Attributes?
Attributes are used to attach metadata to different program elements such as class,
namespace, assembly.
There are predefined attributes provided by C# and custom attributes which developer
can define.
All attributes are derived from the class "System.Attribute" class.
To apply attribute to a program element you add the attribute in square brackets
before the element such as class.For example to add the Obsolete method to a method
you can use:
[Obsolete]
public static void OldMethod() {

}
The information provided by the attribute can be used at compile time and run time to
get more information about the program element. For example serialization attribute
specifies that the program element can be serialized.
Garbage Collection
What is Garbage collection?
When a new object is created it is allocated fixed memory from heap.When the
variable is no longer required then the memory which it occupied is reclaimed and
becomes available.This allocation and deallocation is the job of the garbage collector.
Serialization
What is Serialization?
Serialization is the process of converting object into a format which can be stored in
database or memory or transmitted across a network.This allows the object to be
recreated from the serialized state.
NET provides two types of serialization:
XML
Binary

What is the difference between Dispose and Finalize methods?


Dispose:
Dispose is a method defined in the IDisposable interface
To free unmanaged resources programmer needs to explicitly call dispose()
method.Unmanaged resources are resources such as database connections,file
handles etc.

Finalize:
Automatically called by the garbage collector after the object goes out of
scope.
Belongs to object class.
Encapsulation
Access modifiers?
Access modifiers are keywords for specifying the accessibility of a class or class
members.
public There is no restriction on accessibility.
protected Accessible to the class or the derived class.
internal Accessible to the assembly in which the type is defined.
private Accessible to the class in which the type is defined.
protected internal Accessible to the assembly or the derived class.
Assembly
What is Assembly ?
When a .NET application is compiled ,assembly is generated.Assembly consists of
IL(intermediate language) code.IL is converted to machine code at the execution
time.Apart from IL Assembly also contains Metadata.The metadata describes the
types contained in the assembly and also the assembly details such as the version of
the assembly.There are two main types of assemblies:
private stored inside a folder of the application which uses the assembly.So it
cannot be shared between multiple applications without copying.
shared (public) Stored in the GAC(Global Assembly Cache).Can shared
between different applications without copying to the applications. Strong
name needs to be created for the shared assembly.
What is ILDASM?
ILDASM stands for Intermediate Language Disassembler.It is used for viewing the
IL code in an assembly.For example to view the Intermediate Language Code in a
assembly called Sample.exe use the ildasm as:
ildasm Sample.exe
ildasm.exe is located in the BIN directory of the .NET SDK installation folder. So
you need to add this location to the path variable.
What is Assembly Version number?
Every assembly has a version number which is consists of four decimal pieces:
Major.Minor.Build.Revision
What is strongly named assembly?
A strongly named assembly is used to uniquely identify that assembly, and also
prevents assembly tampering.Strong assembly name consists of the following:
Assembly name,
Assembly version number
Culture information (optional)
Public key
Digital signature.
How do you sign an Assembly with a Strong Name?
To strongly sign an assembly you require a private key corresponding to the public
key.Public key is also distributed with the assembly.The Strong Name tool (Sn.exe)
is used for strongly signing assemblies.
The Assembly Manifest?
Assembly manifest is assembly metadata describing the assembly.It is stored in a PE
file(.dll or .exe) with MSIL code.
It consists of:
● Assembly Name
● Version Number
● Assembly Culture
● Strong name
● List of files in the assembly

The Global Assembly Cache?


Global assembly cache is a cache of assemblies on a machine.GAC is a common
folder consisting of all the assemblies that are shared across different applications.If
you want your assembly to be shared across different applications then you need to
register your assembly in GAC.
For registering an assembly in GAC you use the gacutil command.
Assembly Info.cs?
The metadata about the assembly can be specified in the Assemblyinfo.cs file using
attributes.Some of the attributes which can be defined in Assemblyinfo.cs are:
● AssemblyTitle
● AssemblyDescription
● AssemblyProduct
● AssemblyCompany
Generics
What are Generics?
Generic is a feature introduced in version 2.0 of C#.Generics are used for defining
classes,methods and delegates which work with different data types.This allows the
same class,method or delegate definition to be reused.Generics use type parameters to
accomplish this.Type parameters are placeholders which represents a data type which
is specified by the programmer when the generic object is created.
For example you can use the generic List<> class for integers or strings.
List<int> listInts = new List<int>();
or
List<string> listStrs = new List<string>();
So as declared above the same List type works with both int and string.
Generics provides the following advantages:
Code reusability As the same code works with different data types so you
don't need to write different logic for different data types.
Type safety Since type errors are caught at compile time rather than run time.
Type conversion
Casting in C#?
Casting is used to convert variable of one data type into another data type.Suppose
you have short int value which you want to store in an int variable then casting is
used.
double num=15.6;
int num1;
num1=(int)num;
We are explicitly casting a double value to integer value here.
C# also automatically performs casting in some cases.For example when you perform
type conversions from a variable having smaller range to a variable having larger
range.
.NET framework provides a Convert class to convert one data type to another data
type.
What are the “as” and “is” operators in C#?
is and as operators are used when performing type conversions in C#.You use the is
operator when you want to verify if a variable is of a specific type.For example to
check if a Employee is PermanentEmployee you can use the is operator as:
bool isPermanent =empObj is PermanentEmployee;
Here we are checking if object empObj compatible with PermanentEmployee.If
empObj is derived from PermanentEmployee then isPermanent will be true.
as operator is used to perform conversion from a variable of one type to a variable of
another type if both are compatible else null is returned.
PermanentEmployee permObj = empObj as PermanentEmployee;
Here empObj is converted to PermanentEmployee if it is compatible with
PermanentEmployee else null is returned.
Loops
What is the difference between “continue” and “break” statements in C#?
You use break statement when you want to exit a loop.You use continue when you
want to move to the next iteration of the loop.
for( int count=0; count<100; count++) {
if ( count==10) {
continue;
}
else
{
Console.WriteLine("count="+count);
}
}
The above loop will not execute for the value 10.Instead it goes to the next iteration
and count is not printed for the value 10.If instead we use break statement then the
loop will exit when the count value reaches 10.
Difference between string and StringBuilder class in C#?
The main difference between the two is of immutability.String class is
immutable,which means that any time the string value is modified a new instance or
object of the string class is created.
For example
string name;
name= "C#";
name= "Dotnet";
In the above code two new string objects will be created.
In the case of StringBuilder string modification operation does not create a new
object of the StringBuilder.So if you have lot of string modifications then you should
use StringBuilder as it does not have the overhead of creating new StringBuilder
objects for every modification.
Differences between abstract class and interface
Abstract class is a class which can not instantiated.You need to derive another class
from Abstract class,as its purpose is inheritance by another class.
Interface is a type which consists only of the signature of properties and
methods.Interface can not have any concrete implementation.
Abstract Class Interface
Can consist of abstract as well as Only consists of abstract members
abstract methods and properties
Can consist of variables and other Can not define data members
data members
Members can have access modifiers Members can not have access
such as public,private etc. modifiers.All the members are
public by default.
Differences between enum and struct
Enum Struct
Enum is a group of named constants Similar to a class with function and
data members.But unlike class it is a
value type.
Every Enum derives from Derives from System.ValueType
System.Enum

Difference between readonly and const


Const Readonly
In C# const is declared as a variable Value of a readonly variable can be
and its value can not be changed at changed at runtime inside a
runtime. constructor.
It is mandatory to assign a value to a for readonly it is not mandatory to
const variable when declaring it. assign a value.
Differences between IEnumerable and IQueryable
IEnumerable<T> IQueryable<T>
Query is executed outside the Query is executed in memory.
memory such as database.
Uses LINQ to Objects for query Uses LINQ to SQL or other data
execution. provider based on the datasource.
Doesn’t support lazy loading. Supports lazy loading.

Difference between Array and ArrayList


Array ArrayList
Fixed size,size can not be changed Varaible size.Size can be changed
after declaration. after declaration.
Can store only same type of Can store elements of different data
elements. types as the elements are stored as
objects.
Type conversion is not required as Type conversion is required when
all the elements are of same type. retrieving elements from arraylist as
elements are stored as objects.
What is extension method?
Extension method is used to add functionality to an existing class without modifying
the class. To add functionality to the class you add a static method to a static class. In
the methods first parameter you add the this modifier.
In the following class we are adding extension method called ExtensionMethod in the
SampleStaticClass class.
public static class SampleStaticClass
{
public static void ExtensionMethod(this ExistingClass obj)
{

}
}
Classes
What is a sealed class in c#?
Sealed class is used to prevent further inheritance .If you mark a class as sealed then
it cannot be further inherited.
What are partial classes?
In the case of a partial class the class definition is defined in multiple files.All the
parts defined in the different files are combined when the application is compiled.
What is this keyword?
Collections
How do you sort elements in an array?
You can easily sort elements in a array using the sort() function of the Array
class.Array is the base class of all arrays.So to sort elements in a array called arrItems
you will use:
Array.sort(arrItems)
The sort method of the Array class has overloads.One overload allows you to pass the
IComparer interface.Using an implementation of this interface you can sort the array
based on any property.
In the following example we are sorting Array called intArrayObj.
int[] intArrayObj = { 4, 7, 2, 0 };
var intComparer=new IntComparer();
Array.Sort(intArrayObj, intComparer);

What is IComparer interface?


The above code will sort the array in ascending order.If you want to sort in ascending
order or sort based on different criteria then you can pass an object of IComparer
interface in the sort method.In the following example we are passing an object of a
class implementing IComparer interface.
In the Compare method we have defined the logic on which we want to sort the array
elements.
public class IntComparer : IComparer<int>
{
public int Compare(int firstElement, int secondElement)
{
if (firstElement > secondElement)
return 1;
else if(firstElement < secondElement)
return -1;
else
return 0;
}
}
int[] intArrayObj = { 4, 7, 2, 0 };
var intComparer=new IntComparer();
Array.Sort(intArrayObj, intComparer);
LINQ
What is LINQ?
LINQ stands for language-integrated query.LINQ defines standard query operators
which allows to define queries in any .NET-based programming language.
Before LINQ programmers had to use different technologies for different data
sources.For example if they wanted to query relational data source then you would
use SQL in C# program or if they are working with XML then would use Xpath.If
you are using LINQ then you can use it to query any data source using the same C#
syntax.
Some of the commonly used LINQ operators are:
● Where Used to filter a collection based on a condition.It is implemented as
an extension method which accepts a func delegate as a parameter.
● OrderBy Used for sorting collection based on the given property.
● Select Used for defining the properties of elements returned from a
collection
In the following example we are querying list of Employee objects having a specific
employee id.
class Employee
{
int EmpId;
string Name;
}

string[] emps = { new Employee{


EmpId=1
Name="Marc"
},
new Employee{
EmpId=2
Name="Paul"
}
}
Following will return the employee having EmpId 1:
IEnumerable<Employee> query = from emp in emps
where emp.EmpId == 1
select emp;

What is LINQ Data Provider?


LINQ Data Provider is an interface between LINQ query and the data source.It
allows you to write LINQ queries for a specific data source.There are different LINQ
providers for different data sources such as :
● LINQ to SQL
● LINQ to XML
● LINQ to ADO.NET
Different data providers provide LINQ extension methods for the data sources such
as Select,Where,OrderBy.
What is LINQ to Objects?
In LINQ to Object ,the data source is IEnumerable or IEnumerable<T>.You execute
query on the in-memory collection.
LINQ to Objects allows to write more concise code than foreach loop for performing
operations on a collection.
In the following example array of student objects is declared.Every student object has
a name and marks.We are filtering the students who have scored marks more than
50.
var students=new[]{
new { name="Mark",marks=80},
new { name="John",marks=90},
new { name="Steve",marks=50}
};

var studs = from stud in students


where stud.marks > 50
select stud;

foreach (var stud in studs)


Console.WriteLine(stud);
If you execute the above query then you will get the result as list of students having
marks greater than 50 ,which are Mark and John here.

What is LINQ to SQL?


Using LINQ to Objects we can query the data which is already in memory.Sometimes
we need to work with data which is stored in a persistent storage such as SQL Server.
LINQ to SQL allows to work with data stored in relational databases.To use LINQ to
SQL we need two namespaces:
● System.Data.Linq working with relational databases using LINQ
● System.Data.Linq.Mapping mapping of the database tables and object
model in code
What is DataContext?
DataContext manages connection to the database while using LINQ to SQL.When
creating an object of DataContext we pass a connection string which is used for
connecting to database.
DataContext dataContext = new DataContext(connectionString);
Apart from connecting to the database DataContext also allows to fetch the data from
database and populate the objects.For example to retrieve data from a table called
employee we use dataContext as:
dataContext.GetTable<Employee>()

What is LINQ to XML?


LINQ to XML is a XML interface based on LINQ.This allows to use LINQ queries to
query XML data sources.This means that you can use C# for querying XML data in-
memory.LINQ to XML uses XmlReader behind the scenes.
Another alternative of using LINQ to XML is to use XSLT.But the disadvantage of
XSLT is you will have to use different language then C#.With LINQ to XML you can
use C# for working with XML.
What is IQueryable<T> interface?
It is used in LINQ queries for querying of remote data sources.If a data source
implements IQueryable<T> interface then it can be queried remotely.On the other
hand If the data is of IEnumerable<T> type, you can query it in-memory using LINQ
to Objects.

You might also like