C# Interview Questions & Answers Book
C# Interview Questions & Answers Book
All rights reserved. No part of this book can be reproduced or stored in any retrieval system or transmitted in any
form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning without
the prior written permission of the Dot Net Tricks Innovation Pvt. Ltd.
The author of this book has tried their best to ensure the accuracy of the information described in this book.
However, the author cannot guarantee the accuracy of the information contained in this book. The author or Dot
Net Tricks Innovation Pvt. Ltd. will not be liable for any damages, incidental or consequential caused directly or
indirectly by this book.
Further, readers should be aware that the websites or reference links listed in this book may have changed or
disappeared between when this book was written and when it is read.
All other trademarks referred to in this book are the property of their respective owners.
Release History
• Initial Release 1.0 - 21st Nov 2018
• Second Release 1.1 - 4th Jan 2019
• Third Release 1.2 - 26th Jan 2019
1
Page
About Dot Net Tricks
Dot Net Tricks is founded by Shailendra Chauhan (Microsoft MVP), in Jan 2010. Dot Net Tricks came into existence
in form of a blog post over various technologies including .NET, C#, SQL Server, ASP.NET, ASP.NET MVC, JavaScript,
Angular, Node.js and Visual Studio etc.
The company which is currently registered by a name of Dot Net Tricks Innovation Pvt. Ltd. came into the shape
in 2015. Dot Net Tricks website has an average footfall on the tune of 300k+ per month. The site has become a
cornerstone when it comes to getting skilled-up on .NET technologies and we want to gain the same level of trust
in other technologies. This is what we are striving for.
We have a very large number of trainees who have received training from our platforms and immediately got
placement in some of the reputed firms testifying our claims of providing quality training. The website offers you
a variety of free study material in form of articles.
For a beginner who needs regular guidance, we have a fully packed Master Courses. They are almost equal to
semester courses taught in engineering colleges when it comes to length, breadth of content delivery, the only
difference instead of 5-6 months, they take approx. 16-weekend classes (2 months).
Hands-On Learning courses give you the confidence to code and equally helpful to work in real-life scenarios. This
course is composed of hands-on exercise using IDE or cloud labs so that you can practice each and everything by
yourself. You can learn to code at your own pace, time and place.
The detail about Hands-On Learning courses can be found here: https://www.scholarhat.com
Professionals who don’t have two months’ time and want to get skilled up in least possible time due to some new
project that their company has to take in very near future, we have designed Skill Bootcamps Concept, where you
will get trained on consecutive days in a fast-paced manner, where our full focus is going to be on hands-on
delivery of technological exercises.
Self-paced Courses
2
Self-paced courses give you the liberty to study at your own pace, time and place. We understand everyone has
Page
their own comfort zone, some of you can afford to dedicate 2 hours a day, some of you not. Keeping this thing in
mind, we created these self-paced courses. While creating these courses we have ensured that quality of courses
doesn’t get compromise at any parameter, and they also will be able to produce the same results as our other
course formats, given the fact you will be able to put your own honest effort.
Dot Net Tricks having a pool of mentors who help the corporate to enhance their employment skills as per
changing technology landscape. Dot Net Tricks offers customized training programs for new hires and experienced
employees through online and classroom mode. As a trusted and resourceful training partner, Dot Net Tricks helps
the corporate to achieve success with its industry-leading instructional design and customer training initiatives.
Learning Platform
We have a very robust technology platform to answer the needs of all our trainees, no matter which program they
enrolled in. We have a very self-intuitive Learning Management System (LMS), which help you in remain focused
and keeping an eye over your progress.
Apart from these, we also provide on-demand Skill bootcamps and personalized project consultation.
3
Page
Dedication
My mother Mrs Vriksha Devi and my wife Reshu Chauhan deserve to have their name on the cover as
much as I do for all their support made this possible. I would like to say thanks to all my family members
Virendra Singh(father), Jaishree and Jyoti(sisters), Saksham and Pranay(sons), friends, to you and to
readers or followers of my articles at https://www.dotnettricks.com/mentors/shailendra-chauhan to
encourage me to write this book.
-Shailendra Chauhan
4
Page
Introduction
If you want to crack your C# interview, you’ve come across the right book. This is the book with which you will be
confident to answers the questions on C# language. This book will teach you the C# from beginners to advanced.
This book is designed specifically to teach you the concepts of C# language that can be replaced by any other
modern programming languages, such as Java, C++, PHP or Python.
If you are a working professional or having .NET experience, examine this book in details and see if you are familiar
with all subjects the author has covered. In this book, you will find the answers of most complex questions the
people ask in an interview.
So, what where my qualification to write this book? My qualification and inspiration come from my enthusiasm
for and the experience with the technology and from my analytic and initiative nature. Being a consultant,
corporate trainer, and blogger, I have thorough knowledge and understandings of .NET technologies. My
inspiration and knowledge have also come from many years of my working experience and research over it.
So, the next question is who this book is for? This book is best suited for beginners and professionals. It is
intended for anyone who so far has not engaged seriously in C# programming and would like to start a career in
.NET. This book starts from scratch and teaches you all the core and advanced concepts of C# language in step by
step way. It won't teach you absolutely everything to become a software developer and working at a software
company, but it will help you to turn your programming into your profession.
This book is not only the C# interview book but it is more than that. This book helps you to get an in-depth
knowledge of C# with a simple and elegant way. This book is updated to the latest version of C# 7.3.
I hope you will enjoy this book and find it useful. At the same time, I also encourage you to become a continuous
reader of learning platform www.dotnettricks.com and be the part of the discussion. But most importantly
practice a lot and enjoy the technology. That’s what it’s all about.
To get the latest information on C#, I encourage you to follow the official Microsoft document website at
https://docs.microsoft.com/en-us/dotnet/csharp.
5
Page
About the Author
Shailendra Chauhan - An Entrepreneur, Author, Architect,
Corporate Trainer, and Microsoft MVP
He is the Founder and CEO of DotNetTricks which is a brand when it comes
to e-Learning. DotNetTricks provides training and consultation over an array
of technologies like Cloud, .NET, Angular, React, Node and Mobile Apps
development. He has been awarded as Microsoft MVP three times in a row
(2016-2018).
He has changed many lives from his writings and unique training programs.
He has a number of most sought-after books to his name which have helped
job aspirants in cracking tough interviews with ease.
Moreover, and to his credit, he has delivered 1000+ training sessions to professionals worldwide in Microsoft
.NET technologies and other technologies including JavaScript, AngularJS, Node.js, React and NoSQL Databases.
In addition, he provides Instructor-led online training, hands-on workshop and corporate training programs.
Shailendra has a strong combination of technical skills and solution development for complex application
architecture with proven leadership and motivational skills have elevated him to world-renowned status, placing
him at the top of the list of most sought-after trainers.
“I always keep up with new technologies and learning new skills to deliver the best to my students,” says
Shailendra Chauhan, he goes on to acknowledge that the betterment of his followers and enabling his students to
realize their goals are his prime objective and a great source of motivation and satisfaction.
Shailendra Chauhan - “Follow me and you too will have the key that opens the door to success”
6
Page
How to Contact Us
Although the author of this book has tried to make this book as accurate as it possible but if there is something
strikes you as odd, or you find an error in the book please drop a line via e-mail.
• [email protected]
• [email protected]
We always happy to hear from our readers. Please provide your valuable feedback and comments!
You can follow us on YouTube, Facebook, Twitter, LinkedIn and Google Plus or subscribe to RSS feed.
7
Page
Table of Contents
C# Interview Questions & Answers ................................................................................. 1
Release History ....................................................................................................................................................1
About Dot Net Tricks ...........................................................................................................................................2
Dot Net Tricks Training Solutions .........................................................................................................................2
Dedication ...........................................................................................................................................................4
Introduction ........................................................................................................................................................5
About the Author ................................................................................................................................................6
How to Contact Us...............................................................................................................................................7
Introducing C# ............................................................................................................... 15
Q1. What is C#? .............................................................................................................................................. 15
Q2. Explain evolution history of C#? .............................................................................................................. 15
Q3. What features are added to different versions of C#? ............................................................................ 15
Q4. What is Dynamic binding? ....................................................................................................................... 18
Q5. What are Optional parameters?.............................................................................................................. 18
Q6. What are Named arguments? ................................................................................................................. 18
Q7. What is Type variance?............................................................................................................................ 18
Q8. What are Asynchronous Methods? ......................................................................................................... 18
Q9. Explain the C# code execution process? ................................................................................................. 19
Q10. Can you use out and ref for overloading as the different signature of method? ................................... 25
Page
Statements .................................................................................................................... 38
Q1. What are different types of decision-making statements in C#? ............................................................ 38
Q2. What is if statement in C#? ..................................................................................................................... 38
Q3. What is an if-else statement in C#? ......................................................................................................... 39
Q4. What is If-Else-If statement or ladder in C#?........................................................................................... 40
Q5. What is switch statement or ladder in C#? ............................................................................................. 41
Q6. Which one is fast, switch or if-else-if ladder? ......................................................................................... 43
Q7. What is a loop in C#? ............................................................................................................................... 43
Q8. What is while loop in C#? ........................................................................................................................ 44
Q9. What is do..while loop in C#? .................................................................................................................. 44
Q10. What is for loop in C#? ............................................................................................................................ 45
Q11. What is foreach loop in C#?..................................................................................................................... 45
Q12. What are jump statements? .................................................................................................................... 46
Q13. What is the break statement? ................................................................................................................. 46
Q14. What is the goto statement? ................................................................................................................... 47
Q15. What is the continue statement? ............................................................................................................ 47
Q16. What is the return statement? ................................................................................................................ 48
Q17. What is throw statement?....................................................................................................................... 49
Q18. What are the different types of comment in C#? ................................................................................... 49
Q20. While inheriting a class do the private members get inherited? ............................................................ 66
Page
Q21. What is Enum? ......................................................................................................................................... 66
Q22. When to use enum? ................................................................................................................................ 66
Q23. What is a structure in C#? ....................................................................................................................... 66
Q24. When to use structure? ........................................................................................................................... 68
Q25. What are the similarities between a class and a structure? ................................................................... 68
Q26. What is the difference between class and structure?............................................................................. 68
Q27. What is a static class? .............................................................................................................................. 69
Q28. When to use a static class?...................................................................................................................... 70
Q29. What are static members? ...................................................................................................................... 70
Q30. What is a Static Method? ........................................................................................................................ 70
Q31. What are the differences between static and instance methods? ......................................................... 70
Q32. What are sealed Classes in C#? ............................................................................................................... 71
Q33. What is the base class in .NET Framework from which all the classes are derived? .............................. 71
Q34. What is a partial class, interface or struct? ............................................................................................. 71
Q35. What are the advantages of partial? ....................................................................................................... 72
Q36. What is the partial method?.................................................................................................................... 72
Q37. When to use partial methods? ................................................................................................................ 73
Q8. What are common design guidelines for the interface? ......................................................................... 90
Q9. How can you achieve multiple inheritances (implementation) using interfaces? .................................. 91
Q10. What is the difference between an interface and an abstract class? ..................................................... 92
Threading..................................................................................................................... 104
Q1. What are the thread and process? ........................................................................................................ 104
13
14
Page
1
Introducing C#
Q1. What is C#?
Ans. C# pronounced as "See Sharp". It is an object-oriented programing language developed by Microsoft,
which runs under the .NET platform. Its syntaxes are similar to C++ or Java. The most recent version of C# is 7.3
which is introduced with Visual Studio 2017 update 15.7. C# is widely used for developing web applications,
desktop applications, mobile apps and games etc. Now, C# can be run on Mac, Linux/Unix and Windows using
.NET Core.
C# 2.0
15
• Generics
Page
• Static Classes
• Partial types
• Anonymous methods
• Iterators
• Nullable types
• Asymmetric Property and Indexer Accessors
• Delegate Inference
• Covariance and Contra-variance
C# 3.0
• Implicit types (var)
• Partial Methods
• Anonymous types
• Extension methods
• LINQ
• Query expressions
• Lambda expressions
• Expression trees
• IDE - Visual Studio 2008
C# 4.0
• Dynamic binding
• Named arguments
• Optional Parameters
16
• COM Interop
• IDE -Visual Studio 2010
• .NET Framework - 4.0
C# 5.0
• Asynchronous methods
C# 6.0
• Auto Property Initializer
• Primary Constructors
• Dictionary Initializer
• Declaration Expressions
• Static Using
• await inside catch block
• Exception Filters
• Null-Conditional Operator
• IDE - Visual Studio 2015
• .NET Framework - 4.6
C# 7.0
• Local Functions
• Literal improvements
• Digit Separators
• Pattern matching
IEnumerable<string> str;
//TO DO: assign values to str
Dynamic binding, as well as named and optional arguments, help to make programming against COM less painful
than today. On top of that, however, we are adding a number of other features that further improve the
interoperability experience specifically with COM.
callbacks to capture what happens after an asynchronous process finish. These keywords are used in a
combination of each other and an await operator is applied to a one or more than one expression of an async
Page
method. An async method returns a Task or Task<TResult> that represents the ongoing work of the method.
public async Task<IEnumerable<Product>> GetProductList()
{
HttpClient client = new HttpClient();
Uri address = new Uri("http://dotnet-tricks.com/");
client.BaseAddress = address;
if (response.IsSuccessStatusCode)
{
var list = await response.Content.ReadAsAsync<IEnumerable<Product>>();
return list;
}
else
{
return null;
}
}
19
Page
2
Data Type and Operators
Q1. What is Datatype?
Ans. Data Type refers to the type of data that can be stored in a variable. It also specifies how much memory
would be allocated to a variable and the operations that can be performed on that variable. C# is rich in data type
which is broadly divided into two categories: Value Type and Reference Type.
20
Page
Reference Type - A reference type variable stores a reference to the actual value. Typically, a reference type
contains a pointer to another memory location that stores the actual data. Reference types are of two types
- built-in and user-defined. Reference types are stored in a heap and derived from System.Object class.
Q3. What are Nullable types? How to use Nullable types in .NET Framework?
Ans. Value types that can accept a normal value or a null value are referred to as Nullable types. These are
instances of the Nullable struct.
For example, A Nullable<bool> pronounced as "Nullable of bool" and can have the values true, false or null.
Nullable types can also be defined using ? type modifier. This token is placed immediately after the value type
being defined as nullable.
if (x.HasValue)
{
y = x.Value;
}
Note
You can’t declare an implicitly nullable type variable as nullable like as string type cannot be declared as nullable
21
int
Int16
Int32
Int64
// when x is null, z = y
// when x is not null, z = x
22
/* OutPut
10
Hi Dynamic
12.80
RuntimeBinderException was unhandled, 'double' does not contain a definition for 'Error'
*/
Q8. What are the differences between Object, Var and Dynamic type?
Ans. The differences between Object, Var and Dynamic type are given below:
Key Points
Out - The out keyword also causes an argument to be passed by reference like “ref” keyword, but that argument
can be passed without assigning any value to it.
Key Points
• An argument that is passed using an out keyword must be initialized in the method before it returns back
to calling the method.
• Also, C# properties cannot be passed as an out parameter since internally properties are functions and
function can’t be passed as a parameter.
For example, A program uses ref and out keyword as a method argument.
24
Method2(out arg2);
Console.WriteLine(arg2); // Now 3!
}
static void Method1 (ref int value)
{
value = 1;
}
static void Method2(out int value)
{
value = 2; //must be initialized
}
}
/* Output
1
2
*/
Q10. Can you use out and ref for overloading as the different signature of
method?
Ans. No, you cannot. Although, ref and out are treated differently at runtime they treated same at compile
time. Hence a method cannot be overloaded with the same type of arguments.
{
static decimal Sum(decimal d1, params int[] values)
Page
{
decimal total = d1;
foreach (int value in values)
{
total += value;
}
return total;
}
Console.WriteLine(sum1);
Console.WriteLine(sum2);
Console.WriteLine(sum3);
Console.Read();
}
}
/* Output
11
13
16
*/
Q12. What do you mean by operators and what are different types of
operators in c#?
Ans. An operator is a special symbol that tells to the compiler what operations can be performed on an operand
or between two operands. Operators in programming languages are taken from mathematics.
1. Arithmetic Operators - These operators are used to perform arithmetic operations. The following is a
table of arithmetic operators in C#. Suppose you have two integer variables X, Y and having values 5, 2
respectively then
3. Logical or Boolean Operators – These operators are used to compare values and always result in boolean
value (True or False). The following is a table of logical operators in C#. Suppose you have two boolean
variables X, Y and having values True, False respectively then
5. Assignment Operators – These operators are used to assign a new value to a variable. The following is a
table of assignments operators in C#. Suppose you have two integer variables X, Y with values 5, 2 then
6. Type Information Operators – These operators are used to provides information about a particular type.
The following is a table of type information operators in C#.
Page
Operator Description C# Example
sizeof() Returns the size of a value type. sizeof(int) will give 4
typeof() Returns the type of a class or value type. typeof(bool) will give System.Boolean
Is Determines whether an object is of a certain If (Renault is Car) // checks if Renault is
type or not an object of the Car class.
As Cast an object to a certain type without raising Object obj = new Object();
an exception if the cast fails. // The cast fails: no exception is
thrown and emp is set to null.
Employee emp = obj as Employee;
7. Misc. Operators - There are some more important operators supported by C#. The following is a table of
some Misc operators in C#. Suppose you have two integer variables X, Y and having values 5, 2 then
// when x is null, z = y
// when x is not null, z = x
int z = x ?? y;
it results z = -1
This operator provides an elegant and equivalent syntax to the simple if-else statement.
int number = Convert.ToInt32(Console.ReadLine());
string msg;
// if-else statement
if (number < 0)
msg = "negative";
else
msg = "positive";
A const field is a compile-time constant. A constant field or local variable can be initialized with a constant
expression which must be fully evaluated at compile time.
void Calculate(int Z)
{
const int X = 10, X1 = 50;
const int Y = X + X1; //no error, since its evaluated a compile time
29
const MyClass obj1 = null;//no error, since its evaluated a compile time
const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time
Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.
Readonly - A readonly field can be initialized either at the time of declaration or within the constructor of the
same class. Therefore, readonly fields can be used for run-time constants.
class MyClass
{
readonly int X = 10; // initialized at the time of declaration
readonly int X1;
Explicitly, you can specify a readonly field as static since like constant by default it is not static. The readonly
keyword can be applied to a value type and reference type (which initialized by using the new keyword) both.
Also, delegate and event could not be readonly.
Use the readonly modifier when you want to make a field constant at runtime.
Static - The static keyword is used to specify a static member, which means that static members are common to
all the objects and they do not tie to a specific object.
This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it
cannot be used with indexers, destructors, or types other than classes.
class MyClass
{
static int X = 10;
int Y = 20;
public static void Show()
{
Console.WriteLine(X);
Console.WriteLine(Y); //error, since you can access only static members
}
}
1. If the static keyword is applied to a class, all the members of the class must be static.
Page
2. Static methods can only access static members of the same class. Static properties are used to get or set
the value of static fields of a class.
3. A static constructor can't be parameterized and public. A static constructor is always a private default
constructor which is used to initialize static fields of the class.
Using unsafe keyword of C#, you can mark any of the following as unsafe:
• An entire method.
• A code block in braces.
• An individual statement.
For Example:
class TestUnsafe
{
unsafe static void PointerMethod()
{
int i = 5;
int* pt = &i;
System.Console.WriteLine("*pt = " + *pt);
System.Console.WriteLine("Address of pt = {0:X2}\n", (int)pt);
}
unsafe
{
int* pt = &i;
System.Console.WriteLine("*pt = " + *pt);
System.Console.WriteLine("Address of pt = {0:X2}\n", (int)pt);
}
}
1. Implicit conversion – Implicit conversion is being done automatically by the compiler and no data will be
lost. It includes conversion of a smaller data type to a larger data types and conversion of derived classes
to base class. This is safe type conversion.
class Base
{
public int num1 { get; set; }
}
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
//Implicit Conversion
Base b = d;
}
}
2. Explicit conversion - Explicit conversion is being done by using a cast operator. It includes conversion of
the larger data type to smaller data type and conversion of the base class to derived classes. In this
conversion information might be lost or conversion might not be succeeding for some reasons. This is un-
safe type conversion.
class Base
{
public int num1 { get; set; }
32
}
Page
class Program
{
static void Main(string[] args)
{
Base b = new Base();
//Explicit Conversion
Derived d = (Derived)b;
}
}
3. User-defined conversion - User-defined conversion is performed by using special methods that you can
define to enable explicit and implicit conversions. It includes conversion of class to a struct or basic data
type and struct to class or basic data type. Also, all conversions methods must be declared as static.
class RationalNumber
{
int numerator;
int denominator;
}
}
Q19. How to do safe type casting in C#?
Or
What are the differences between IS and AS operators in C#?
Ans. Type Casting is the mechanism to convert one data type to another. And so, while explicit type casting of
one data type to another, we get an exception if the previous one data type is not compatible with the new data
type. To avoid this exception, we have IS and AS operator in C# for safe typecasting.
• IS Operator - The IS operator checks whether the type of a given object is compatible with the new object
type. It returns Boolean type value: true if the given object is compatible with new one, else false. In this
way IS operator help you to do safe typecasting.
class Employee
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Creates a new Object obj
Object obj = new Object();
// checking compatibility of obj object with other type
// b1 is set to true.
Boolean b1 = (obj is Object);
// The cast fails: no exception is thrown, but b2 is set to false.
Boolean b2 = (obj is Employee);
In the above example, CLR is checking the type of obj object twice. First time within IF Condition and if it
is true, then a second time within IF Block. Actually, this way affects the performance since each and every
time CLR will walk the inheritance hierarchy, checking each base type against the specified type
(Employee). To avoid this, we have AS operator.
• AS Operator - The AS operator also checks whether the type of a given object is compatible with the new
object type. It returns non-null if the given object is compatible with new one, else null. In this way AS
34
operator help you to do safe typecasting. The above code can be re-written by using AS operator in a
Page
better way.
class Employee
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Creates a new Object obj
Object obj = new Object();
// checking compatibility of obj object with other type
In the above example, CLR checks the obj object type only one time; if it is matched it returns non-null
means Employee type otherwise returns null. Hence AS operator provide good performance over IS
operator.
Note - AS operator used only for reference conversions, nullable conversions, and boxing conversions.
This operator cannot perform other conversions like as user-defined conversions.
class Program
{
static void Main(string[] args)
{
Derived d1 = new Derived();
//Upcasting
Base b1 = d1;
35
Page
}
}
Unboxing - Explicit conversion of same reference type (which is being created by boxing process), back to a value
type is known as unboxing. In the unboxing process, the boxed value type is unboxed from the heap and assigned
to a value type which is being allocated on the stack.
For Example:
// int (value type) is created on the Stack
int stackVar = 12;
// Unboxing = boxed int is unboxed from the heap and assigned to an int stack variable
int unBoxed = (int)boxedVar;
Note:
• Sometimes boxing is necessary, but you should avoid it if possible since it will slow down the performance and
increase memory requirements.
For example, when a value type is boxed, a new reference type is created and the value is copied from the
value type to the newly created reference type. This process takes time and required extra memory (around
twice the memory of the original value type).
• Attempting to unbox null causes a NullReferenceException.
// NullReferenceException
int unBoxed = (int)boxedVar; //Object reference not set to an instance of an object.
// InvalidCastException
float unBoxed = (float)boxedVar; //Specified cast is not valid.
37
Page
3
Statements
Q1. What are different types of decision-making statements in C#?
Ans. Decision-making statements help you to make a decision based on certain conditions. These conditions
are specified by a set of decision-making statements having Boolean expressions which are evaluated to a Boolean
value true or false. There are following types of decision-making statements in C#.
Conditional
Statements
If-Else If-Else-If or
If Statement Switch
Statement Ladder
38
Page
You can have multiple if statement as shown below-
public class Example
{
static void Main()
{
int a = 5, b = 2;
int result = a / b;
if (result == 2)
{
Console.WriteLine("Result is 2");
}
if (result == 3)
{
Console.WriteLine("Result is 3");
}
}
}
/* Output
Result is 2
*/
You can also do nesting of if statement means an if statement inside another if that is called nested if statement.
39
Page
public class Example
{
static void Main()
{
int a = 5, b = 6;
int result = a - b;
if (result > 0)
{
Console.WriteLine("Result is greater than zero");
}
else
{
Console.WriteLine("Result is smaller than or equal to zero");
}
}
}
/* Output
Result is smaller than or equal to zero
*/
40
Page
If-Else-If ladder must contain more specific case at the top and generalize case at the bottom.
public class Example
{
static void Main(string[] args)
{
char grade = 'B';
if (grade == 'A')
{
Console.WriteLine("Excellent!");
}
else if (grade == 'B')
{
Console.WriteLine("Well done");
}
else if (grade == 'D')
{
Console.WriteLine("You passed");
}
else if (grade == 'F')
{
Console.WriteLine("Better try again");
}
else
{
Console.WriteLine("You Failed!");
}
}
}
/* Output
Well done
*/
When one case matches the value with the result of switch expression, the control continues executing the code
from that label. When no case label contains a matching value, control is transferred to the default section, if it
exists. When there is no default case, no action is taken and control is transferred outside to the switch statement.
public class Example
{
static void Main(string[] args)
{
char grade = 'B';
switch (grade)
{
41
case 'A':
Console.WriteLine("Excellent!");
Page
break;
case 'B':
case 'C':
Console.WriteLine("Well done");
break;
case 'D':
Console.WriteLine("You passed");
break;
case 'F':
Console.WriteLine("Better try again");
break;
default:
Console.WriteLine("You Failed!");
break;
}
}
}
/* Output
Well done
*/
42
Page
The key point about the Switch statement
Loop
Statements
43
Print Number : 5
Do you want to continue (Y/N) :n
Page
*/
Q10. What is for loop in C#?
Ans. This loop has three sections - index declaration, condition (Boolean expression) and updation section. In
each for loop iteration, the index is updated (incremented/decremented) by updation section and checked with
the condition. If the condition is matched, it continues execution until the specified Boolean expression evaluates
to false.
Typically, for loop is useful when you are aware of an exact number of iterations. Normally, it is used for iterating
over arrays and for sequential processing.
public class Example
{
static void Main(string[] args)
{
int[] arr = new int[5] { 5, 10, 12, 20, 30 };
Typically, Foreach is used in place of for loop where you need to retrieve the elements from the source collection,
but it cannot be used to add or remove items from the source collection. For adding or removing items from the
source collection, you should use for loop.
public class Example
{
static void Main(string[] args)
{
int[] arr = new int[5] { 5, 10, 12, 20, 30 };
}
/* Output:
Page
Number is :5
Number is :10
Number is :12
Number is :20
Number is :30
*/
Above foreach loop statement is equivalent to the following while loop statement –
int[] arr = new int[5] { 5, 10, 12, 20, 30 };
Jump
Statements
}
Console.WriteLine("Next statement placed after loop");
Page
}
}
/* Output:
1
2
3
4
Next statement placed after loop
*/
This statement is also used to terminates an inner nested loop and return control to the outer loop.
Note: Unlike the break statement, it does not transfer the program control to the next statement which is placed
immediately after the loop or switch.
This statement is not recommended since it makes the program logic complex and difficult to understand. It also
becomes difficult to trace the control flow of program execution.
Ans. This statement skips the current iteration and passes the program control to the next iteration of the
Page
Unlike break statement, it does not terminate the loop execution but it skips the current iteration of the loop and
passes program control to the next iteration of the enclosing loop.
If the return statement appears in a try block and the finally block is also existing, then the finally block will be
Page
49
Page
4
Array and Strings
Q1. What do you mean by an Array?
Ans. An array is a collection of homogenous or same types of elements which are accessible by a numeric index.
The numeric index starts from 0 and goes to n-1, where n is the size of an array.
An array is stored in contiguous memory locations and the memory lowest address contains the first element and
the highest memory address contains the last element in an array.
For example,
int[] arr = new int[5]; // declare arr as an int type array of size 5
arr[0] = 6;
arr[1] = 8;
arr[2] = 4;
arr[3] = 3;
arr[4] = 2;
50
Page
Q2. Explain different types of arrays in C#
Ans. There are three types of arrays in C# as given below-
Types of
Arrays
For example,
int[] arr = new int[5]; // declare single dimensional array
arr[0] = 6;
arr[1] = 8;
arr[2] = 4;
arr[3] = 3;
arr[4] = 2;
arr2D[0, 0] = 1;
arr2D[0, 1] = 2;
arr2D[0, 2] = 3;
arr2D[1, 1] = 4;
arr2D[1, 2] = 5;
51
arr2D[1, 3] = 6;
Page
arr2D[2, 1] = 7;
arr2D[2, 2] = 8;
arr2D[2, 3] = 9;
arr3D[0, 0, 0] = 1;
arr3D[0, 0, 1] = 2;
arr3D[0, 0, 2] = 3;
arr3D[0, 1, 0] = 1;
arr3D[0, 1, 1] = 2;
arr3D[0, 1, 2] = 3;
arr3D[0, 2, 0] = 1;
arr3D[0, 2, 1] = 2;
arr3D[0, 2, 2] = 3;
arr3D[1, 0, 0] = 1;
arr3D[1, 0, 1] = 2;
arr3D[1, 0, 2] = 3;
arr3D[1, 1, 0] = 1;
arr3D[1, 1, 1] = 2;
arr3D[1, 1, 2] = 3;
arr3D[1, 2, 0] = 1;
arr3D[1, 2, 1] = 2;
arr3D[1, 2, 2] = 3;
arr3D[2, 0, 0] = 1;
arr3D[2, 0, 1] = 2;
arr3D[2, 0, 2] = 3;
arr3D[2, 1, 0] = 1;
arr3D[2, 1, 1] = 2;
arr3D[2, 1, 2] = 3;
arr3D[2, 2, 0] = 1;
arr3D[2, 2, 1] = 2;
arr3D[2, 2, 2] = 3;
In the jagged array, it is necessary to specify the value in the first bracket [] since it specifies the jagged array size.
You can also mix jagged array and multi-dimensional array to declare an array as given below-
int[][,] mixedArray = new int[3][,] {
new int[,] { {1,3}, {5,7} },
new int[,] { {0,2}, {4,6}, {8,10} },
new int[,] { {11,22}, {99,88}, {0,9} }
};
It provides various useful methods such as CreateInstance, Copy, CopyTo, GetValue, and SetValue, Sort and
others properties such as LongLength and GetLongLength for manipulating an array.
int[] arr = new int[] { 4, 12, 6, 1 }; //declare a unorder array
Array.Sort(arr); //sorting unorder array arr
1. It is a reference type.
2. It can contain a null value.
3. It is immutable means you cannot change the contents of a string.
For example,
string str = "Hello World";
str = str.Replace("World", "Dot Net Tricks");
In the above example, you are not changing the original string (Hello World) contents which str contains. But it’s
just setting the value of str to a new string which is a copy of the old string "World" is replaced by "Dot Net Tricks".
The new string has been allocated to a new memory address that is different from old string address.
The String class provides many methods for creating, manipulating, and comparing strings. You should not use the
new operator to create a string object except when initializing the string with an array of chars as given below-
53
2. Immutable string - Immutable strings are instances of System.String class. You cannot modify the contents
of a mutable string i.e. whenever you perform any text manipulation on an immutable string, a new string
object is returned and original string remains same. It is extremely useful with regard to trust since a string
would not change as long as you don't change your reference.
using System;
using System.Text;
class Example
{
static void Main(string[] args)
{
//original string is: Hello World
string immutableStr = "Hello World";
/* Output:
Hello World
Hello Dot Net Tricks
Hello Dot Net Tricks
*/
54
Page
Q10. What is the difference between System.String and
System.Text.StringBuilder classes?
Ans. Differences between string and StringBuilder are given below-
System.String System.Text.StringBuilder
Represents immutable string. Represents mutable string.
It is extremely useful with regard to trust since a It is extremely useful when you need to perform a lot of
string would not change as long as you don't change text manipulation on the string.
your reference.
Console.WriteLine(str);
Console.WriteLine(strverbatim);
}
}
/* Output:
c:\Program Files\Microsoft.NET
c:\Program Files\Microsoft.NET
*/
class Book
{
//Attributes
int BookId;
string Title;
string Author;
string Subject;
double Price;
//Behaviours
public void showDetails()
{
Console.WriteLine("\n########## Book Details ##########");
}
Page
}
public class Program
{
public static void Main(string[] args)
{
//object creation and initialization
Book objBook1 = new Book(1, "ASP.NET MVC Interview Questions & Answers",
"Shailendra Chauhan", ".NET ", 500);
Book objBook2 = new Book(2, "Node.js Interview Questions & Answers ", "Shailendra
Chauhan", "JavaScript", 400);
//calling class
objBook1.showDetails();
objBook2.showDetails();
Console.ReadKey();
}
}
/* Output
For example, a student object can have attributes name, address and contact number. It performs activities
attending class, giving exam etc.
Key points
57
1. Default Constructor - The default constructor has no parameter. When a class has no constructor, the
default constructor is served by the compiler to that class.
2. Parameterized Constructor - The parameterized constructor has one or more arguments and used to
assign values to instance variables of the class.
class Example
{
double num1, num2;
//Default Constructor
public Example()
{
Console.WriteLine("This is a default constructor!");
}
//Parameterized Constructor
public Example(int a, int b)
{
num1 = a;
num2 = b;
Console.WriteLine("This is a paremeterized constructor!");
}
//Parameterized Constructor
public Example(double a, double b)
{
num1 = a;
num2 = b;
Console.WriteLine("This is a paremeterized constructor!");
}
#endregion
class Program
58
{
static void Main()
Page
{
Example obj1 = new Example(); //default constructor called
Example obj2 = new Example(4, 5); //parameterized constructor called
Example obj3 = new Example(4.2, 5.2); //parameterized constructor called
obj2.ShowResult();
obj3.ShowResult();
Console.Read();
}
}
/* Output
This is a default constructor!
This is a parameterized constructor!
This is a parameterized constructor!
Result: 9
Result: 9.4
*/
3. Copy Constructor – This constructor is used to copy the entire values of an object to another object. But
C# does not support copy constructor.
Key points
• Only one static constructor is allowed and it must be a default constructor having no access modifier i.e.
private access. The class may have others non-static parameterized constructors.
• It can only access the static member.
• It is used to write the code that needs to be executed only once.
• A static constructor cannot be called directly.
class Example
{
static int Count;
double num1, num2;
{
59
num1 = a;
num2 = b;
Page
class Program
{
static void Main()
{
Example obj2 = new Example(4, 5); //parameterized constructor called
Example obj3 = new Example(4.2, 5.2); //parameterized constructor called
obj2.ShowResult();
obj3.ShowResult();
Console.Read();
}
}
/* Output
This is a static constructor!
This is a parameterized constructor!
This is a parameterized constructor!
Result: 10
Result: 10.4
*/
Q7. Why you can have only one static Constructor in a class?
Ans. To define multiple constructors for a class, you need to overload the constructors. It means you need to
define parameterized constructors that accept parameters from outside but the static constructor is called by the
CLR and CLR cannot pass parameters to the parameterized constructor. So, only one static constructor is possible
in a class.
class Program
{
static void Main()
{
// Example obj = new Example(); //Error private constructor is inaccessible
Initial count = 1
New count = 2
*/
Q9. When you create child class object, which class constructor will be called
first?
Ans. When you create a child class object, first its base class constructor is called then its constructor is called.
Public class BaseClass
{
public BaseClass()
{
Console.WriteLine("Base class constructor!");
}
61
}
Page
class ExecutionClass
{
static void Main()
{
ChildClass objChild = new ChildClass();
Console.ReadKey();
}
}
/* Out put
*/
//destructor
~Example()
{
Console.WriteLine("Destructor called to destroy instance");
}
}
class Program
{
static void Main()
{
Example T = new Example();
GC.Collect();
62
}
}
Page
/*Out Put
Constructor called.
Destructor called to destroy the instance
*/
Implement it when you have unmanaged resources in your code and want to make sure that these resources are
freed when the Garbage collection happens.
// Implementing Finalize method
class Example
{
public Example()
{
Console.WriteLine("Constructor called");
}
Q12. What are the similarities and difference between finalize and destructor?
Ans. Finalize and destructor, both are used to release unmanaged resources allocated by the object. The
differences between these two are given below-
• Finalize method corresponds to the .NET framework and it is a part of System.Object class whereas
destructor is the C# implementation of the finalize method.
• In C#, destructors are converted to finalize method when the program is compiled.
{
string connectionString = "Persist Security Info=False;Integrated
Page
/* Output
*/
When you would not use the using statement, you need to write code to clean up the specified resources for
releasing occupied memory as given below-
using System;
using System.Data.SqlClient;
finally
{
Page
/* Output
Name: Mohan, Address: Noida, Mobile: 9500000000
Name: Rohan, Address: Delhi, Mobile: 9400000000
*/
1. Private – A private member can only be accessed inside the same class or struct. By default, a class or a
struct members have private access. Also, private members are not accessible outside the containing class
or struct.
2. Protected - A protected member can only be accessed inside the same class or in a class that is derived
from that class. A class member can be declared as protected but a struct members cannot be declared
as protected since struct does not support inheritance.
3. Public - A public member can be accessed inside the same assembly or any other assembly that references
it. A class or a struct members can be declared as public. By default, interface members are public and
you cannot define any access modifier to interface members.
4. Internal - An internal member can be accessed inside the same assembly, but not within any other
assembly. A class or a struct members can be declared as internal. By default, class, struct, interface,
delegates itself have internal access when declared inside a namespace. A class, struct, interface,
delegates itself have private access when nested.
5. Protected Internal - A protected member can be accessed inside the same assembly, or inside a derived
class in another assembly. A class member can be declared as protected internal but a struct members
cannot be declared as protected internal because structs do not support inheritance.
Q16. Can a child or derived type have higher accessibility form its parent type?
Ans. No, it cannot. You cannot have a public class B that has been derived from an internal class A. It would be
a compile time error.
65
Ans. No, struct members cannot be declared as protected. This is because structs do not support inheritance.
Q18. Can you explain the member's Accessibility?
Ans. Access modifiers accessibly can be understood through the following table:
By default, the first enumerator value starts from 0 and the successive enumerators values increased by 1.
enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };
In the above Days enum, Sat is 0, Sun is 1, Mon is 2, and so on. You can also change the default values for
enumerators, as shown in the following example.
enum Days { Sat=2, Sun, Mon, Tue, Wed, Thu, Fri };
Now, the first enumerator value will start from 2 and each successive enumerator value will increase by 1.
structure types.
Page
struct Book
{
int BookId;
string Title;
string Author;
string Subject;
double Price;
public void getDetails(int bookId, string title, string author, string subject,
double price)
{
BookId = bookId;
Title = title;
Author = author;
Subject = subject;
Price = price;
}
public void showDetails()
{
Console.WriteLine("\n########## Book Details ##########");
Book1.showDetails();
Book2.showDetails();
Console.ReadKey();
}
}
/* Output
BookId :1
Page
Features of structure:
• Like a class, a struct can have methods, fields, indexers, properties, operator methods, events and nested
structure.
• A struct can have only default constructors.
• A struct cannot have destructors. Since it is a value type and there is no need to call GC.
• Unlike a class, a struct does not support inheritance but it can implement one or more interfaces.
• By default, a struct is sealed; hence cannot be inherited by another type.
• A struct cannot have abstract, virtual or protected access modifiers. Since these access modifiers are used
with the members of a base type but a struct cannot work as a base type.
• Unlike a class, a struct can be instantiated without using the new operator. In this case, struct fields will
remain unassigned and the struct instance cannot be used until all the fields are initialized.
• Both can have constructors, methods, properties, fields, constants and enum,
• Both can implement the interface.
• Both can have delegates and events.
Class Structure
/*Output
*/
Q28. When to use a static class?
Ans. A static class is useful when you want to provide some common utilities like various configuration settings,
driver manipulation etc. to your application.
class Program
{
static void Main()
{
Example obj1 = new Example();
//obj1.MyMethod(); //error, MyMethod cannot be accessed by class instance, use
type name instead
Example.MyMethod();
Console.Read();
}
}
/*Output
Count =2
Hi, I am a static method, called directly by class name!
*/
Q31. What are the differences between static and instance methods?
70
Ans. Static Method: A static method is declared using a static modifier and can have access to the static
Page
members only. It is called by the class name and you cannot use this keyword with it.
Instance Method: Other methods in a class are instance methods. An instance method is called using the class
object and can access both static and non-static members. It cannot be called directly by its class name and you
can use this keyword with it.
Q33. What is the base class in .NET Framework from which all the classes are
derived?
Ans. System.Object.
// Partial Interface
71
void ITest();
}
partial interface IExample
{
void ITest2();
}
// Partial Structure
partial struct SExample
{
void STest()
{
//write your code
}
}
partial struct SExample
{
void STest2()
{
//write your code
}
}
1. During code compilation, all the files should be available to form the final class, interface or struct.
2. Any member declared in the one part/file will be available to all other parts.
3. If any part has Inheritance, then it applies to the entire class.
4. Different parts of a class or struct may inherit from different interfaces.
5. If any part is declared abstract, then the whole class, interface or struct is considered abstract.
6. If any part is declared sealed, then the whole class, interface or struct is considered sealed.
1. Allow more than one developer to work simultaneously on the same class, struct or interface.
2. Partial class are particularly helpful for customizing auto-generated code by the IDE. Whenever the IDE
generate the code then the tool may define some partial class, interface, methods and further
customization of a partial class, the interface is done by the developers without messing with the system
generated code.
1. Partial methods can be declared or defined within the partial class or struct.
2. Partial methods are implicitly private and declarations must have the partial keyword.
3. Partial methods must return void.
4. Partial methods implementation is optional.
5. Partial methods can be static and unsafe and generic.
6. Partial methods can have ref parameters but not out parameters since these can't return value.
7. You cannot make a delegate to a partial method.
8. The signatures of the partial method will be the same in both parts of the partial class or struct.
If you are using entity framework for making DAL then you have seen that the Visual Studio make a partial method
OnContextCreated() as shown below. Now, the implementation of it depends on you whether you want to use it
or not.
public partial class DALEntities : ObjectContext
{
#region Constructors
// Constructors for DALentities
#endregion
#region Partial Methods
partial void OnContextCreated();
#endregion
}
// This part can be put in the separate file
public partial class DALEntities : ObjectContext
{
partial void OnContextCreated()
{
// put method implementation code
Debug.WriteLine("OnContextCreated partial method");
}
}
73
Page
6
Exception Handling
Q1. What is Error?
Ans. Errors refer to the mistake or faults which occur during program development or execution. If you don't
find them and correct them, they cause a program to produce wrong results.
1. Syntax Errors - Syntax errors occur during development when you make type mistake in the code. For
example, instead of writing while, you write WHILE then, it will be a syntax error since C# is a case-sensitive
language.
bool flag=true;
2. Runtime Errors (Exceptions) - Syntax errors occur during execution of the program. These are also called
exceptions. This can be caused due to improper user inputs, improper system errors.
int a = 5, b = 0;
int result = a / b; // DivideByZeroException
3. Logical Errors - Logic error occurs when the program is written fine but it does not produce the desired
result. Logic errors are difficult to find because you need to know for sure that the result is wrong
int a = 5, b = 6;
double avg = a + b / 2.0; // logical error, it should be (a + b) / 2.0
Ans. Exceptions are defined as glitches, unexpected or unseen errors which occur during the execution of a
program. These can be caused due to improper user inputs, improper design logic or system errors. In this case,
Page
if an application does not provide a mechanism to handle these exceptions then your application may crash.
Q4. What are different types of Exceptions?
Ans. Exceptions can be of following two types -
Property Usage
InnerException Provides exception instance that caused the current exception.
Message Provides detailed information about the error
StackTrace Provides the function stack to show where the exception is thrown
Source Provides the name of the application or the object that causes the error.
Targetsite Shows which method throws the current exception
System.ArithmeticException A base class for handling exceptions that occur during arithmetic
operations.
System.DivideByZeroException and System.OverflowException classes
inherit this class.
System.DivideByZeroException Thrown when an attempt to divide a numeric value by zero.
System.IndexOutOfRangeException Thrown when an attempt to access an array element via an index that is
less than zero or outside the bounds of the array.
System.InvalidCastException Thrown when an explicit conversion from a base type to a derived type
fails at runtime.
System.NullReferenceException Thrown when the referenced object is null but it is required.
System.OutOfMemoryException Thrown when an attempt to allocate memory (via new) fails.
System.StackOverflowException Thrown when the execution stack is exhausted by having too many
pending method calls; typically, a very deep or recursion method calls.
Try Block - The try block encloses the statements that might throw an exception.
try
{
// Statements that can cause exception.
}
Catch Block - The catch block handles any exception if one exists.
catch(ExceptionType e)
{
// Statements to handle exception.
}
Finally Block - The finally block can be used for doing any clean-up process like releasing unused resources even
if an exception is thrown. For example, Disposing database connection.
finally
{
// Statement to clean up.
}
catch (Exception e)
{
throw (e);
}
try
{
// statements that can cause exception.
}
catch (MoreSpecificExceptionType e1)
{
// error handling code
76
}
catch (SpecificExceptionType e2)
Page
{
// error handling code
}
catch (GeneralExceptionType eN)
{
// error handling code
}
finally
{
// statement to clean up.
}
try
{
// statements that can cause exception.
}
catch (MoreSpecificExceptionType e1)
{
// error handling code
}
catch (SpecificExceptionType e2)
{
// error handling code
}
catch (GeneralExceptionType eN)
{
// error handling code
}
try
{
// statements that can cause exception.
}
finally
{
// statement to clean up.
}
/* Output
User-defined exception!
Catching Exception: Exception of type 'UserDefinedException' was thrown.
Next statement to be executed
*/
• To get the type from an existing object and invoke its methods or access its fields and properties
• Need to perform late binding, accessing methods on types created at runtime.
serialization.
Q7. What are Serializable and NonSerialized attributes?
Ans. In .NET Framework, SerializableAttribute attribute to serialize all the members of a class. If you do not
want to serialize a member, decorate that member with NonSerializedAttribute. Let’s understand these things
with the help of the following examples:
Using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
1. XML Serialization - This serialization serializes an object into an XML stream. This is best for cross-platform
transfer since XML is supported by every platform. This generates a human-readable and editable data
file.
2. Binary Serialization - This serialization uses binary encoding. It is faster and secure than XML serialization
but it is not easily portable to another platform except .NET.
3. SOAP Serialization - This serialization serializes the object into XML stream which follows the SOAP
specification. A SOAP is an XML based protocol to transport procedure calls using XML.
Unlike fields, properties do not denote storage locations and you cannot pass a property as a ref or out parameter.
using System;
class Example
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main()
{
Example obj = new Example();
obj.Name = "Dot Net Tricks"; // called set { }
Console.WriteLine(obj.Name); // called get { }
}
}
1. Read-Only Property - A read-only property allows you to only retrieve the value of a field. To create a
read-only property, you should define the get accessor.
class User
{
string name;
public string Name
{
get { return name; }
}
}
2. Write-Only Property - A write-only property allows you to only change the value of a field. To create a
write-only property, you should define the set accessor.
class User
{
string name;
public string Name
{
set { name = value; }
}
}
3. Read-Write Property - A read-write property allows you to assign and read the value of a field. To create
a read-write property, you should define the set and get accessors.
class User
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
To make an auto-implemented property read-only or write-only, you need to specify both get and set accessors.
Page
}
class Student: Person
{
private string name;
}
84
{
private string name;
Just like methods, an indexer can be overloaded and can multiple parameters with a different type. Unlike an
array, an indexer cannot be passed as a ref or out parameter.
class Program
{
static void Main(string[] args)
{
Example names = new Example();
names[0] = "Shailendra";
names[1] = "Aman";
names[2] = "Pavan";
names[3] = "Mohan";
names[4] = "Deepak";
Console.ReadKey();
}
class Example
{
static public int size = 10;
private string[] namelist = new string[size];
{
tmp = namelist[index];
Page
}
else
{
tmp = "";
}
return (tmp);
}
set
{
if (index >= 0 && index <= size - 1)
{
namelist[index] = value;
}
}
}
}
/* Output
Shailendra
Aman
Pavan
Mohan
Deepak
*/
• The operations which need to access the network resources or the file system or database operations.
• The operations return an array.
• The operation is a type conversion, such as ToString() method.
Property Indexer
It is identified by its name. It is identified by its signature.
Can be a static or an instance member. Must be an instance member.
Accessed through a simple name. Accessed through an index.
A get accessor of a property has no parameters. A get accessor of an indexer has the same
parameters as it has.
A set accessor of property has an implicit value A set accessor of an indexer has the same parameters
parameter. as it has, along with the value parameter.
Supports shortened syntax using Auto-Implemented Does not support shortened syntax.
86
Properties.
Page
9
Abstract Class and Interface
Q1. What is an abstract Class?
Ans. An abstract class is a special type of class which cannot be instantiated and acts as a base class for other
classes. Abstract class members declared as abstract must be implemented by the derived classes.
For example,
abstract class ShapesClass
{
abstract public int Area();
}
87
int side = 0;
public Square(int n)
{
side = n;
}
// Override Area method
public override int Area()
{
return side * side;
}
}
Another need of abstract is to create multiple versions of your component since versioning is not a problem with
the abstract class. You can add properties or methods to an abstract class without breaking the code and all
inheriting classes are automatically updated with the change.
1. Don't define public constructors inside the abstract class. Since an abstract class cannot be instantiated.
2. Define a protected or an internal constructor inside an abstract class. Since a protected constructor allows
the base class to do its own initialization when derived classes are instantiated. An internal constructor
will limit the implementation of the abstract class to the same assembly which contains that class.
declaration or signature and implicitly every member of an interface is public and abstract.
Page
For example, the most common use of interfaces is, within SOA (Service Oriented Architecture). In SOA (WCF), a
service is exposed through interfaces to different clients. Typically, an interface is exposed to a group of clients
which needs to use common functionalities.
interface IStore
{
void Read();
void Write();
}
interface ICompress
{
void Compress();
void Decompress();
}
#endregion // IStore
#region ICompress
1. The main issue with an interface is that when you add a new member to its, then you must implement
those members within all of the classes which implement that interface.
2. Interfaces are slow as these required extra in-directions to find the corresponding method in the actual
class.
1. Keep your interfaces focused on the problem you are trying to solve and keep related tasks (methods)
into an interface. Interfaces that have multiple unrelated tasks tend to be very difficult to implement in a
class. Split up interfaces that contain unrelated functionality.
90
2. Make sure your interface does not contain too many methods. Since too many methods make
implementing the interface difficult as the implementing class has to implement each and every method
Page
in the interface.
3. Don't make interfaces for specific functionality. An interface should define the common functionality that
can be implemented by the classes of different modules or subsystems.
I1 i1 = (I1)obj;
i1.Show();
I2 i2 = (I2)obj;
i2.Hide();
Console.ReadKey();
}
}
/*
Output
*/
Q10. What is the difference between an interface and an abstract class?
Ans. The differences between an interface and an abstract class are given below-
The interface has only the member’s declaration or An abstract class contains at least one abstract member
signature and implicitly every member of an and others, non-abstract members. Like a simple class,
interface is public and abstract. It contains only an abstract class can have data members and member
properties, indexers, methods, delegates and events functions.
signature
It cannot contains constants members, constructors, It can contains constants members, constructors,
destructors, instance variables, static members or destructor, instance variables, static members or
nested interfaces. nested class.
It can have only public member. It can have public, protected and private member.
Methods have only declaration. It can have non abstract method with body definition.
Static and Instance constants are possible. Only static constants are possible.
It supports multiple inheritances and so a class can It does not support multiple inheritances and so a class
inherit more than one interface. can inherit only one abstract class.
Use an interface when you need to provide common Use an abstract class when you need to create multiple
functionality to unrelated classes and to create versions of your component and to provide default
loosely coupled components, easily maintainable behaviours as well as common behaviours that multiple
and pluggable components because the derived classes can share and override.
implementation of an interface is separated from
itself.
92
Page
10
Delegates and Events
Q1. What are Delegates?
Ans. A delegate is a reference type that holds the reference to a class method. Any method which has the same
signature as a delegate can be assigned to delegate. It is very similar to the function pointer but with a difference
that delegates are type-safe. We can say that it is the object-oriented implementation of function pointers.
• Delegates are like C++ function pointers but they are type safe.
• Delegates allow methods to be passed as parameters.
• Delegates are used in event handling for defining callback methods.
• Delegates can be chained together i.e. these allow defining a set of methods that can be executed as a
single unit.
• Once a delegate is created, the method it is associated will never change because delegates are immutable
in nature.
• Delegates provide a way to execute methods at runtime.
• All delegates are implicitly derived from System.MulticastDelegate, class which is inheriting from
System.Delegate class.
• Delegate types are incompatible with each other, even if their signatures are the same. These are
considered equal if they have the reference of the same method.
1. Declaration - A delegate is declared by using the keyword delegate, otherwise it resembles a method
declaration.
2. Instantiation - To create a delegate instance, we need to assign a method (which has the same signature
as a delegate) to delegate.
3. Invocation - Invoking a delegate is like as invoking a regular method.
//1. Declaration
public delegate int MyDelagate(int a, int b); //delegates having the same signature as a
93
method
Page
// 3.Invocation
Console.WriteLine("Sum of two integer is = " + sum(10, 20));
Console.WriteLine("Difference of two integer is = " + diff(20, 10));
}
}
/* Output
Sum of two integer is = 30
Difference of two integer is = 10
*/
1. Single cast delegate - A single cast delegate holds the reference of the only a single method. In the
previous example, the created delegate is a single cast delegate.
2. Multicast delegate - A delegate which holds the reference of more than one method is called the multicast
delegate. A multicast delegate only contains the reference of methods which return type is void. The +
and += operators are used to combine delegate instances. Multicast delegates are considered equal if
they reference the same methods in the same order.
//1. Declaration
public delegate void MyDelagate(int a, int b);
public class Example
{
// methods to be assigned and called by the delegate
public void Sum(int a, int b)
94
{
Console.WriteLine("Sum of integers is = " + (a + b));
Page
}
public void Difference(int a, int b)
{
Console.WriteLine("Difference of integer is = " + (a - b));
}
}
class Program
{
static void Main()
{
Example obj = new Example();
// 2. Instantiation
MyDelagate multicastdel = new MyDelagate(obj.Sum);
multicastdel += new MyDelagate(obj.Difference);
// 3. Invocation
multicastdel (50, 20);
}
}
/* Output
Sum of integers is = 70
Difference of integer is = 30
*/
Console.WriteLine("C#.NET");
}
Page
}
/*Output
VB.NET
C#.NET
MS-SQL
*/
class MyEventHandler
{
public event EventHandler EventRaised; //declaration of event handler
public void RaiseAnEvent()
{
EventHandler handler = EventRaised; // instance
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
class MyEventObserver
{
public void MyMethodHandleEvent(object sender, EventArgs args) // event
{
Console.WriteLine("Event occurred at " + sender);
}
}
class ExecutionClass
{
static void Main()
96
{
MyEventHandler objHandler = new MyEventHandler();
Page
Events Delegates
While defining interface we can use events We can’t use delegate in the interface definition.
An event can only be invoked from the class that Delegates can be invoked from derived classes and
declares it. clients.
The event comes with its pair of assessors i.e. Add No such accessors are required here.
and Remove. Which is assigned and unassigned
with a += and -= operator.
The event has a restrictive signature and must Delegates are not bounded of such restrictive signature.
always be of the form
Event(object sender, EventArgs args)
will be serialized.
NonSerialized Class, struct, enum, delegate Specifies that all public and private fields of this type can
Page
be serialized.
Obsolete All, except Assembly, Specify a type or method obsolete i.e. it informs to the user
Parameter, and Return Type that this one will be removed in future versions of the code.
Q11. How to show a message in your latest version of code about your old
method removal?
Ans. This can be handled using Obsolete attribute as given below:
For example,
public class Example
{
[Obsolete("This method is obsoleted, use NewShow method", true)]
public void Show()
{
//To DO:
}
public void NewShow()
{
//To DO:
}
}
class Program
{
static void Main(string[] args)
{
Example obj = new Example();
obj.Show();
}
}
When you will run this program, you will get the following error as given below-
{
this.name = name;
address = "Delhi";
}
}
[AuthorInfo("Shailendra Chauhan", address = "Noida")]
class Author
{
// TO DO:
}
The custom attribute class name may or may not have attribute suffix; it is optional.
99
Page
11
Collections and Generics
Q1. What are Collections?
Ans. A collection is a set of related objects. Unlike arrays, a collection can grow and shrink dynamically as the
number of objects added or deleted. A collection is a class, so you must declare a new collection before you can
add elements to that collection.
Class Description
In generics, a generic type parameter is supplied between the open (<) and close (>) brackets and which makes it
Page
strongly typed collections i.e. generics collections contain only similar types of objects.
Q4. What are the advantages of generics?
Ans. There are following advantages of generics:
Class Description
Q7. What are the differences between Generic Collections and Non-Generic
Collections in C#?
Ans. The differences between generic and non-generic collections are given below-
Store elements of same data types. Can store elements of different data types.
101
The .NET Framework provides various concurrent collections like ConcurrentDictionary<Key, Value>,
ConcurrentStack<T>, ConcurrentQueue<T>, ConcurrentBag<T> etc.
Class Description
Q9. What is the name of the namespace for concurrent collections in C#?
Ans. The concurrent collections exist in System.Collections.Concurrent namespace.
IEnumerable acts as a base interface for all the collection types that is extended by ICollection. ICollection is
further extended by IDictionary and IList.
102
Page
Interface Description
IEnumerable Provides an enumerator which supports a simple iteration over a non-generic collection.
ICollection Defines size, enumerators and synchronization methods for all non-generic collections.
IDictionary Represents a non-generic collection of key/value pairs.
IList Represents a non-generic collection of objects that can be individually accessed by index.
All collections interfaces are not implemented by all the collections classes. It depends on the collection class
behaviours. For example, the IDictionary interface would be implemented by only those collection classes which
support key/value pairs, like HasTable and SortedList etc.
103
Page
12
Threading
Q1. What are the thread and process?
Ans. As per MSDN “A thread is a basic unit to which the operating system allocates processor time”. A thread
can execute any part of the executing program which is known as a process. One or more threads can be used to
execute a process and share a process virtual address space and system resources.
104
Page
State Description
Unstarted Represents initial state and thread is not started yet.
Started Represents a thread has been started by invoking Thread.Start() method.
Running Represents a thread is running.
Stopped Represents a thread has been finished.
Represents a thread is blocked. This might be because of calling Thread.Sleep() or Thread.Join()
WaitSleepJoin
methods, or requesting a lock.
Suspended Represents a thread has been suspended.
Aborted Represents a thread has been aborted i.e. it is dead. But its state is changed to Stopped.
For example, you can use one thread to monitor input from the user, second thread to perform background
tasks, third thread to process user input and fourth thread to show the output of the third thread processing.
threads management.
The .NET Framework ThreadPool class is used to implement a thread pool. This is a static class that you can directly
Page
access.
Thread pooling provides you better performance and better system stability when you need to create or destroy
too many threads for your applications.
106
Page
References
107
Page