CSHARP C# Interview Questions & Answers
CSHARP C# Interview Questions & Answers
Coding exercise…
List of top 500 C# csharp Interview Questions & Answers....Coding exercise questions are coming
soon!!
18
stars
16
forks
Star
Notifications
master
Go to file
View code
Table of Contents
No. Questions
3 What is debugging?
Name different types errors which can occur during the execution of a
4
program?
8 What is flowchart?
https://github.com/kansiris/C-Sharp-c-interview-question 1/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
No. Questions
9 What is an algorithm?
10 What do you understand by the term 'Maintain and update the Program'?
17 What is Documentation?
23 Define Operators.
24 What is an Array?
25 What is subroutine?
32 What is reliability?
https://github.com/kansiris/C-Sharp-c-interview-question 2/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
No. Questions
49 What is a data type? How many types of data types are there in .NET ?
Mention the two major categories that distinctly classify the variables of C#
50
programs.
54 What is an identifier?
https://github.com/kansiris/C-Sharp-c-interview-question 3/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
No. Questions
63 What is C#?
64 What is an Object?
https://github.com/kansiris/C-Sharp-c-interview-question 4/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
No. Questions
99 What is Serialization?
https://github.com/kansiris/C-Sharp-c-interview-question 5/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
No. Questions
122 How can you sort the elements of the array in descending order?
What’s the .NET collection class that allows an element to be accessed using a
123
unique key?
125 Will the finally block get executed if an exception has not occurred?
127 Can multiple catch blocks be executed for a single try statement?
128 Explain the three services model commonly know as a three-tier application?
130 Can you prevent your class from being inherited by another class?
Can you allow a class to be inherited, but prevent the method from being over-
131
ridden?
Why can’t you specify the accessibility modifier for methods inside the
133
interface?
What happens if you inherit multiple interfaces and they have conflicting
135
method names?
What’s the implicit name of the parameter that gets passed into the set
136
method/property of a class?
https://github.com/kansiris/C-Sharp-c-interview-question 6/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
No. Questions
Can you declare an override method to be static if the original method is not
137
static?
What’s the implicit name of the parameter that gets passed into the class’ set
140
method?
143 When you inherit a protected class-level variable, who is it available to?
147 What’s the top .NET class that everything is derived from?
148 What does the keyword virtual mean in the method definition?
Can you declare the override method static while the original method is non-
149
static?
Why can’t you specify the accessibility modifier for methods inside the
152
interface?
No. Questions
168 What is the default Accessmodifier for the members of the class?
if we declare Main() and static constructor in the same class which one will be
172
called first?
How to Call the Default constructor of one class with the parameterised
173
constructor of same class?
https://github.com/kansiris/C-Sharp-c-interview-question 8/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
No. Questions
In .net for Assemblies we are having StrongName lly in COM Components what
185
is the Strongname?
https://github.com/kansiris/C-Sharp-c-interview-question 9/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
No. Questions
PROGRAMMING CONCEPT
What is Computer programming?
Computer Programming is also known as programming or coding. Programming is a
process which includes processes such as coding, maintaining, updating, debugging,
writing, designing (algorithm), etc.
What is debugging?
Debugging is the process of finding and removing errors in a program. In this process, the
program is thoroughly checked for errors. Then errors are pointed out and debugged.
Name different types errors which can occur during the execution of a
program?
There are three types of errors which can occur during the execution of a program.
Syntax Errors
Runtime Errors
Logical errors
https://github.com/kansiris/C-Sharp-c-interview-question 10/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
What is flowchart?
The flowchart is a pictorial representation of a program which helps in understanding the
flow of control and data in the algorithm.
https://github.com/kansiris/C-Sharp-c-interview-question 11/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Reserved words or keywords are the words, which have predefined meanings. They have
predefined uses and cannot be used or redefined for any other purpose in a programming
language.
Examples
IF
ELSE
THEN
FOR…NEXT Loop
WHILE…WEND Loop
Nested Loop
details%3Fid%3Din.togetu
https://github.com/kansiris/C-Sharp-c-interview-question 12/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Numeric Constants
String Constants
https://github.com/kansiris/C-Sharp-c-interview-question 13/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
An array is a collection of contiguous memory locations which can store data of the same
type.
Write a code in 32-bit x86 machine code to calculate the nth Fibonacci number.
8B542408
83FA0077 06B80000 0000C383FA027706 B8010000 00C353BB 01000000B9010000
008D0419 83FA0376 078BD98BC84AEBF1 5BC3
A+
https://github.com/kansiris/C-Sharp-c-interview-question 14/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
A++
ACC
ALF
APL
BASIC
COBOL
EXPRESS
Flowchart
https://github.com/kansiris/C-Sharp-c-interview-question 15/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Software testing a process in which software is tested under certain conditions to test the
quality of a program. Testing a program is also required to check whether the software
provides a good user experience or not.
Tell a few reasons of software testing.
Proper working
Satisfying quality
Get data
Perform computation
Display results
<Data_type> <variable_name> ;
A constant is similar to a variable except that the value, which you assign to a constant,
cannot be changed, as in case of a variable.
Constants must be initialized at the same time they are declared. You can declare constants
by using the following syntax:
https://github.com/kansiris/C-Sharp-c-interview-question 17/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Question: What is a data type? How many types of data types are there
in .NET ?
A data type is a data storage format that can contain a specific type or range of values.
Whenever you declare variables, each variable
must be assigned a specific data type. Some
common data types include integers, floating point, characters, and strings. The following
are the two types of data types available in .NET:
Value type - Refers to the data type that contains the data. In other words, the exact value or
the data is directly stored in this data type. It means that when you assign a value type
variable to another variable, then it copies the value rather than copying the reference of
that variable. When you create a value type variable, a single space in memory is allocated
to store the value (stack memory). Primitive data types, such as int, float, and char are
examples of value type variables.
Reference type - Refers to a data type that can access data by reference. Reference is a value
or an address that accesses a particular data by address, which is stored elsewhere in
memory (heap memory). You can say that reference is the physical address of data, where
the data is stored in memory or in the storage device. Some built-in reference types
variables in .Net are string, array, and object.
Question: Mention the two major categories that distinctly classify the
variables of C# programs.
Variables that are defined in a C# program belong to two major categories: value type and
reference type. The variables that are based on value type contain a value that is either
allocated on a stack or allocated in-line in a structure. The variables that are based on
reference types store the memory address of a variable, which in turn stores the value and
are allocated on the heap. The variables that are based on value types have their own copy
of data and therefore operations done on one variable do not affect other variables. The
reference-type variables reflect the changes made in the referring variables.
int x = 42;
int y = 12;
int w;
object o;
o = x;
w = y * (int)o;
Console.WriteLine(w);
https://github.com/kansiris/C-Sharp-c-interview-question 18/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
namespace UserNameSpace;
Namespace UserNameSpace
switch(choice)
{
case 1:
console.WriteLine(First);
break;
case 2:
console.WriteLine(Second);
break;
default:
console.WriteLine(Wrong choice);
break;
}
In switch statements, the break statement is used at the end of a case statement. The break
statement is mandatory in C# and it avoids the fall through of one case statement to
another.
https://github.com/kansiris/C-Sharp-c-interview-question 19/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
The new keyword is universally used in C# and Visual Basic to implement encapsulation by
creating objects.
3.Value types have an implicit default constructor that initializes the default value of that
type
int i = 0;
i++;
o/p: 0 1 2 3 4
https://github.com/kansiris/C-Sharp-c-interview-question 20/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
1.Value type - Refers that you do not need to provide any keyword with a parameter.
2.Reference type - Refers that you need to mention the ref keyword with a parameter.
3.Output type - Refers that you need to mention the out keyword with a parameter.
4.Optional parameter - Refers to the new parameter introduced in C# 4.0. It allows you to
neglect the parameters that have some
5. Named parameter - Refers to the new parameter introduced in C# 4.0. Now you can
provide arguments by name rather than position.
The example of the named parameter is as follows: - public void CreateAccount(string name,
string address = unknown, int age = 0);
1.Class - Refers to the primary building block for the programs, which is used to encapsulate
variables and methods into a single unit.
https://github.com/kansiris/C-Sharp-c-interview-question 21/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
1.Boolean Literals - Refers to the True and False literals that map to the true and false state,
respectively.
2.Integer Literals - Refers to literals that can be decimal (base 10), hexadecimal (base 16), or
octal (base 8).
4.String Literals - Refers to a sequence of zero or more Unicode characters beginning and
ending with an ASCII double-quote character.
7.Nothing - Refers to a literal that does not have a type and is convertible to all types in the
type system.
1.Boolean literals - Refers to the True and False literals that map to the true and false states,
respectively.
2.Integer literals - Refers to literals that are used to write values of types int, uint, long, and
ulong.
3.Real literals - Refers to literals that are used to write values of types float, double, and
decimal.
5.String literals - Refers to string literals, which can be of two types in C#:
i. A regular string literal consists of zero or more characters enclosed in double quotes, such
as hello.
ii. A verbatim string literal consists of the @ character followed by a double-quote character,
such as @hello.
https://github.com/kansiris/C-Sharp-c-interview-question 22/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
We can also provide arguments in a sub-procedure; however, it does not return a new
value.The function is also a set of statements within the Function and End Function
statements.It is similar to sub - procedure and performs the same task.The main difference
between a function and a sub - procedure is that sub - procedures do not return a value
while functions do.
int a = 29;
a--;
a -= ++a;
o/p: -1
Boxing and unboxing enable value types to be treated as objects. Boxing a value type
packages it inside an instance of the Object reference type. This allows the value type to be
stored on the garbage collected heap. Unboxing extracts the value type from the object. In
this example, the integer variable iis boxed and assigned to object obj.
Boxing Example:
console.writeline(o); }
Unboxing Example:
{object o =111;
https://github.com/kansiris/C-Sharp-c-interview-question 23/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
console.writeline(i); }
CSharp (C#)
Question: What is C#?
C# is the best language for writing Microsoft .NET applications. C# provides the rapid
application development found in Visual Basic with the power of C++. Its syntax is similar to
C++ syntax and meets 100% of the requirements of OOPs like the following:
• Abstraction
• Encapsulation
• Polymorphism
• Inheritance
Struct
Class
• The class is reference type in C# and it inherits from the System.Object Type.
What is an Interface?
An interface contains only the signatures of methods, properties, events or indexers. A class
or struct that implements the interface must implement the members of the interface that
are specified in the interface definition. In the following example,
class ImplementationClass must implement a method named SampleMethod that has no
parameters and returns void.
An interface is not a class. It is an entity that is defined by the word Interface. An interface
has no implementation; it only has the signature or in other words, just the definition of the
methods without the body. As one of the similarities to Abstract class, it is a contract that is
used to define hierarchies for all subclasses or it defines specific set of methods and their
arguments. The main difference between them is that a class can implement more than one
interface but can only inherit from one abstract class. Since C# doesn't support multiple
inheritance, interfaces are used to implement multiple inheritance.
When we create an interface, we are basically creating a set of methods without any
implementation that must be overridden by the implemented classes. The advantage is that
it provides a way for a class to be a part of two classes: one from inheritance hierarchy and
one from the interface.
https://github.com/kansiris/C-Sharp-c-interview-question 25/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
When we create an abstract class, we are creating a base class that might have one or more
completed methods but at least one or more methods are left uncompleted and
declared abstract. If all the methods of an abstract class are uncompleted then it is same as
an interface. The purpose of an abstract class is to provide a base class definition for how a
set of derived classes will work and then allow the programmers to fill the implementation
in the derived classes.
interface ISampleInterface
{ void SampleMethod(); }
class ImplementationClass :
ISampleInterface
{ // Explicit interface member implementation:
void
ISampleInterface.SampleMethod()
{ // Method implementation.
}
static void Main()
{ //
Declare an interface instance.
ISampleInterface obj = new ImplementationClass();
// Call the
member.
obj.SampleMethod();
} }
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A
class may inherit only one abstract class.
Default implementation
An interface cannot
provide any code, just the signature.
An abstract class can provide complete, default code
and/or just the details that have to be overridden.
Access Modifiers
An interface cannot
have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
Core VS
Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words
both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the
core identity of a class and there it is used for objects of the same type.
Homogeneity
If
various implementations only share method signatures then it is better to use Interfaces.
If
various implementations are of the same kind and use common behaviour or status then
abstract class is better to use.
Speed
Requires more time to find the actual method in the
corresponding classes.
Fast
Adding functionality (Versioning)
If we add a new method to an
Interface then we have to track down all the implementations of the interface and define
implementation for the new method.
If we add a new method to an abstract class then we
have the option of providing default implementation and therefore all the existing code
might work properly.
Fields and Constants
No fields can be defined in interfaces
An abstract
class can have fields and constraints defined
An enum type can be an integer (float, int, byte, double etc.). But if you used beside int it
has to be cast.
An enum is used to create numeric constants in .NET framework. All the members of enum
are of enum type. There must be a numeric value for each enum type.
https://github.com/kansiris/C-Sharp-c-interview-question 26/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
The default underlying type of the enumeration element is int. By default, the first
enumerator has the value 0, and the value of each successive enumerator is increased by 1.
• Enums are not for end-user, they are meant for developers.
• Enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may
not be implicitly assigned to an enum of
another type even though the underlying value of
their members is the same.
• Enumerations (enums) make your code much more readable and understandable.
• Enum values are fixed. Enum can be displayed as a string and processed as an integer.
• The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long,
and ulong.
• Every enum type automatically derives from System.Enum and thus we can use
System.Enum methods on enums.
• Enums are value types and are created on the stack and not on the heap.
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace break_example
{
{
Class brk_stmt
{
if (i == 4) {continue; }
}
}
}
}
Output:
The number is 0;
The number is 1;
The number is 2;
The number is 3;
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace continue_example
{
Class cntnu_stmt
{
public static void main(String[]
{
for (int i = 0; i <= 5; i++)
if (i == 4)
continue;
}
}
}
Output:
The number is 1;
The number is 2;
The number is 3;
The number is 5;
https://github.com/kansiris/C-Sharp-c-interview-question 28/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Constants:
3.Constants should be used when it is very unlikely that the value will ever change.
Read-only:
We have a Test Class in which we have two variables one is readonly and another is
constant.
class Test {
}
}
Here I was trying to change the value of both the variables in constructor but when I am
trying to change the constant it gives an error to change their value in that block which
have to call at run time.
So finally remove that line of code from class and call this Check() function like the following
code snippet:
class Program {
}
}
class Test {
}
}
Output:
Ref
Passing a parameter value by ref is useful when the called method is also needed to modify
the pass parameter
A parameter value must be initialized within calling method before its use
Out
Declaring a parameter to an out method is when multiple values need to be returned for
function or method
When we use out data is passed only in unidirectional way (from the called method caller )
https://github.com/kansiris/C-Sharp-c-interview-question 30/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Static methods (or any static member) do not belong to a particular instance. They exist
without creating an instance of the class and call with the name of a class not by instance so
we can’t use this keyword in the body of static Methods, but in case of Extension Methods
we can use it the functions parameters. Let’s have a look on “this” keyword.
The "this" keyword is a special type of reference variable that is implicitly defined within
each constructor and non-static method as a first parameter of the type class in which it is
defined. For example, consider the following class written in C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace this_example
{
class Program
{
public class Demo
{
int age;
string name;
public Demo(int age, string name)
{
age = age;
name =
name;
}
public void Show()
{
Console.WriteLine("Your age is :" +
age.ToString());
Console.WriteLine("Your name is : " + name);
} }
static void Main(string[] args)
{
int _age;
string _name;
obj.Show();
Console.ReadLine();
} }}
See your not getting any value. Because in the program the local data members age, name
have precedence over instance members.
Note the program will give a warning not error (Assignment made to some variable; did you
mean to assign something else?)
https://github.com/kansiris/C-Sharp-c-interview-question 31/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace this_example
{
class Program
{
public class Demo
{
int age;
string name;
public Demo(int age, string name)
{ // Have made change here
included this keyword
this.age = age; this.name = name; }
public void Show()
{ Console.WriteLine("Your age is :" +
age.ToString());
Console.WriteLine("Your name is : " + name); } }
static void Main(string[] args)
{ int _age; string _name;
obj.Show();
Console.ReadLine();
} } }
The program is not complete implementation of this keyword but it tries to make you
explain how it works and when to use.
https://github.com/kansiris/C-Sharp-c-interview-question 32/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
The get and set portions or blocks of a property are called accessors. These are useful to
restrict the accessibility of a property, the set accessor specifies that we can assign a value to
a private field in a property and without the set accessor property it is like a read-only field.
By the get accessor we can access the value of the private field, in other words it returns a
single value. A Get accessor specifies that we can access the value of a field publicly.
• Read/Write.
• ReadOnly.
• WriteOnly
Extension methods are only in scope when you explicitly import the namespace into your
source code with a using directive.
Like: suppose we have a class like below:
Now we need to extend the definition of this class so m going to create a static class to
create an extinction method like:
https://github.com/kansiris/C-Sharp-c-interview-question 33/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Here I just create a method that name is NewMethod with a parameter using this to define
which type of data I need to be extend, now
let’s see how to use this function.
class Program {
String:
String is an immutable object. Immutable like when we create string object in code so we
cannot modify or change that object in any
operations like insert new value, replace or
append any value with existing value in string object, when we have to do some operations
to change string simply it will dispose the old value of string object and it will create new
instance in memory for hold the new value
in string object like:
val += “am”;
console.writeline(val);
}
}
Note:
• Performance wise string is slow because its’ create a new instance to override or change
the previous value.
https://github.com/kansiris/C-Sharp-c-interview-question 34/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
StringBuilder:
System.Text.Stringbuilder is mutable object which also hold the string value, mutable means
once we create a System.Text.Stringbuilder
object we can use this object for any operation
like insert value in existing string with insert functions also replace or append
without
creating new instance of System.Text.Stringbuilder for every time so it’s use the previous
object so it’s work fast as compare
than System.String. Let’s have an example to understand
System.Text.Stringbuilder like:
class program
{
static void main(string[]args)
{
val.append(“hello);
console.writeline(val);}}
Note:
• Performance wise StringBuilder is very fast because it will use same instance of
StringBuilder object to perform any operation like insert value in existing string.
String Example
string colors;
colors += "red";
colors += "blue";
colors += "green";
In the above code string color will alter 3 times, each time the code perform a string
operation (+=). That mean 3 new string created in the memory. When you perform
repeated operation to a string, the overhead associated with creating a new String object
can be costly.
StringBuilder Example
sb.Append("red");
https://github.com/kansiris/C-Sharp-c-interview-question 35/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
sb.Append("blue");
sb.Append("green ");
In the above code the StringBuilder object will alter 3 times, each time the code attempt a
StringBuilder operation without creating a new object. That means, using the StringBuilder
class can boost performance when concatenating many strings together in a loop.
Delegates are especially used for implementing events and the call-back methods. All
delegates are implicitly derived from the
System.Delegate class.
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the Not
Inheritable keyword serves the purpose of sealed. If a class is derived from a sealed class
then the compiler throws an error.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
// Sealed class
sealed class SealedClass
{ }
https://github.com/kansiris/C-Sharp-c-interview-question 36/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Partial Classes can be create in the same namespace it’s doesn’t allowed to create a partial
class in different namespace. So use “partial” keyword with the entire class name which you
want to bind together with the same name of class in same namespace, let’s have an
example:
RunTime Polymorphism or Late Binding: Runtime polymorphism also known as late binding,
in Run Time polymorphism or Late Binding we can do use same method names with same
signatures means same type or same number of parameters but not in same class because
compiler doesn’t allowed that at compile time so we can use in derived class that bind at
run time when a child class or derived class object will instantiated that’s way we says that
Late Binding.
For that we have to create my parent class functions as partial and in driver or child class as
override functions with override keyword.
https://github.com/kansiris/C-Sharp-c-interview-question 37/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
IEnumerable:
Is the parent interface for all non-generic collections in System.Collections namespace like
ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as
IEnumerable which a parent interface of all generic collections class in
System.Collections.Generic namespace like List< > and more.
IQueryable:
The IQueryable interface inherits the IEnumerable interface so that if it represents a query,
the results of that query can be enumerated. Enumeration causes the expression tree
associated with an IQueryable object to be executed. The definition of "executing an
expression tree" is specific to a query provider. For example, it may involve translating the
expression tree to an appropriate query language for the underlying data source. Queries
that do not return enumerable results are executed when the Execute method is called.
Ienumerable
iqueryable
ienumerable is the best way to write query on collections data type like list,array etc
iqueryable is the best way to write query data like remote database,service collections
ienumerable is the return type for linq to object and linq to xml queries
ienumerable doesnt support lazy loading so it's not a recommended approach for paging
kind of scenarios
iquerable support lazy loading so we can also use in paging kind of scenarios
extension methods are supports by ienumerable takes funtional objects for linq querys
https://github.com/kansiris/C-Sharp-c-interview-question 38/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
example:
interface testInterface1 {
void Show(); }
interface testInterface2 {
void Show(); }
testInterface2 {
void testInterface1.Show() {
void testInterface2.Show() {
class Program {
obj1.Show();
obj2.Show();
Console.ReadLine(); } }
Arrays are powerful data structures for solving many programming problems. You saw
during the creation of variables of many types that they have one thing in common; they
hold information about a single item, for instance an integer, float and string type and so
on. So what is the solution if you need to manipulate sets of items? One solution would be
to create a variable for each item in the set but again this leads to a different problem. How
many variables do you need?
So in this situation Arrays provide mechanisms that solves problem posed by these
questions. An array is a collection of related items, either value or reference type. In C#
arrays are immutable such that the number of dimensions and size of the array are fixed.
Arrays Overview-
An array contains zero or more items called elements. An array is an unordered sequence of
elements. All the elements in an array are of the same type (unlike fields in a class that can
be of different types). The elements of an array accessed using an integer index that always
starts from zero. C# supports single-dimensional (vectors), multidimensional and jagged
arrays.
Elements are identified by indexes relative to the beginning of the arrays. Indexes are also
commonly called indices or subscripts and are placed inside the indexing operator ([]).
Access to array elements is by their index value that ranges from 0 to (length-1).
Array Properties
https://github.com/kansiris/C-Sharp-c-interview-question 40/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Clone - Method creates a shallow copy of an array. A shallow copy of an Array copies only
the elements of the Array, whether they are reference types or value types, but it does not
copy the objects that the references refer to. The references in the new Array point to the
same objects that the references in the original Array point to.
CopyTo - The Copy static method of the Array class copies a section of an array to another
array. The CopyTo method copies all the elements of an array to another one-dimension
array. The code listed in Listing 9 copies contents of an integer array to an array of object
types.
using System;
class MyClient {
int x = 0;
int div = 0;
Console.WriteLine("DivideByZeroException");
Console.WriteLine("Exception");
} finally {
Console.WriteLine("Finally Block"); }
Throw basically retains the stack information and adds to the stack information in the
exception that it is thrown.
Let us see what it means rather speaking so many words to
better understand the differences. I am using a console application to easily test and see
how the usage of the two differs in their functionality.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestingThrowExceptions {
class Program {
try {p.ExceptionMethod(); }
throw ex;
}
}
}
}
Now run the code by pressing the F5 key of the keyboard and see what happens. It returns
an exception
An indexer, also called an indexed property, is a class property that allows you to access a
member variable of a class using the features of an array.
Defining an indexer allows you to create classes that act like virtual arrays. Instances of that
class can be accessed using the [] array access operator.
https://github.com/kansiris/C-Sharp-c-interview-question 42/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Creating an Indexer:
this[argument list] {
• The return type of the delegate must be void. None of the parameters of the delegate
type can be delegate type can be declared as output parameters using out keywords.
• Multicast delegate instance that created by combining two delegates, the invocation list is
formed by concatenating the invocation list of two operand of the addition operation.
Delegates are invoked in the order they are added.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class DM {
Console.WriteLine("Meerut") }
Console.WriteLine("Roorkee"); } }
https://github.com/kansiris/C-Sharp-c-interview-question 43/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
class MTest {
MDelegate m3 = m1 + m2;
MDelegate m4 = m2 + m1;
MDelegate m5 = m3 - m2;
using System;
namespace ComparisionExample {
class Program {
Console.ReadKey();
https://github.com/kansiris/C-Sharp-c-interview-question 44/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
class Speaker {
class Author {
• In the preceding, we are just checking the matching type. Yes, our speaker is an
object of Speaker type.
"as" operator-
The "as" operator behaves similar to the "is" operator. The only difference is it returns the
object if both are compatible to that
type else it returns null.
We have a method that accepts dynamic objects and returns the object name property if
the object is of the Author type.
https://github.com/kansiris/C-Sharp-c-interview-question 45/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Declaration:
Any DataType can be declared nullable type with the help of operator "?".
int? i = null;
As discussed in previous section "var" is not compatible with this Nullable Type. So we will
have Compile Time error if we are
declaring something like:
var? i = null;
var i = 4;
Example:
https://github.com/kansiris/C-Sharp-c-interview-question 46/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Hello_Word {
class overloding {
Console.WriteLine(volume(10));
Console.WriteLine(volume(2.5F, 8));
Console.ReadLine();
Note:
If we have a method that have two parameter object type and have a same name
method with two integer parameter so when we call that method with int value so it’ll call
that method have integer parameter instead of object type parameters method.
Object Pool is nothing but a container of objects that are ready for use. Whenever there is a
request for a new object, the pool manager will take the request and it will be served by
allocating an object from the pool.
How it works?
We are going to use Factory pattern for this purpose. We will have a factory method, which
will take care about the creation of objects. Whenever there is a request for a new object,
the factory method will look into the object pool (we use Queue object). If there is any
object available within the allowed limit, it will return the object (value object), otherwise a
new object will be created and give you back.
https://github.com/kansiris/C-Sharp-c-interview-question 47/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Generics allow you to delay the specification of the data type of programming elements in a
class or a method, until it is actually used in the program. In other words, generics allow you
to write a class or method that can work with any data type.
You write the specifications for
the class or the method, with substitute parameters for data types. When the compiler
encounters a constructor for the class or a function call for the method, it generates code to
handle the specific data type.
Generic classes and methods combine reusability, type safety and efficiency in a way that
their non-generic counterparts cannot.
Generics are most frequently used with collections and the methods that operate on them.
Version 2.0 of the .NET Framework class library provides a new namespace,
Features of Generics:
• You can create generic collection classes. The .NET Framework class library contains several
new generic collection classes in the
System.Collections.Generic namespace. You may use these generic collection classes instead
of the collection classes in the System.Collections namespace.
• You can create your own generic interfaces, classes, methods, events and delegates.
• You may create generic classes constrained to enable access to methods on specific data
types.
• You may get information on the types used in a generic data type at run-time using
reflection.
Access modifiers are an integral part of object-oriented programming. They support the
concept of encapsulation, which promotes the idea of hiding functionality. Access modifiers
allow you to define who does or doesn't have access to certain features. In C# there are 5
different types of Access Modifiers:
https://github.com/kansiris/C-Sharp-c-interview-question 48/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Modifier
Description
Public
Private
Access is limited to within the class definition. This is the default access modifier type if
none is formally specified
Protected
Access is limited to within the class definition and any class that inherits from the class
Internal
Access is limited exclusively to classes defined within the current project assembly
Protected internal
When a method is declared as a virtual method in a base class then that method can be
defined in a base class and it is optional for the derived class to override that method. The
overriding method also provides more than one form for a method. Hence it is also an
example for polymorphism.
When a method is declared as a virtual method in a base class and that method has the
same definition in a derived class then there is no need to override it in the derived class.
But when a virtual method has a different definition in the base class and the derived class
then there is a need to override it in the derived class.
When a virtual method is invoked, the run-time type of the object is checked for an
overriding member. The overriding member in the most derived class is called, which might
be the original member, if no derived class has overridden the member.
https://github.com/kansiris/C-Sharp-c-interview-question 49/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Virtual Method:
2. We can't use the virtual modifier with the static, abstract, private or override modifiers.
ArrayList
Arraylist has many methods to do operation like sort insert, remove, binarysearch, etc
https://github.com/kansiris/C-Sharp-c-interview-question 50/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
• Pure Value Type: Here I used a structure as a value type. It has an integer member. I
created two instances of this structure. Afterwards I assigned second instance to the first
one. Then I changed the state of second instance, but it hasn't effect the first one, as whole
items are value type and assignments on those types will copy only values not references i.e.
in a Value Type assignment, all instances have its own local copy of members.
• Pure Reference Type: I created a class and added a "DataTable" as a Reference Type
member for this class. Then I performed the assignments just like below. But the difference
is that on changing the state of second instance, the state of first instance will automatically
alter. So in a Reference Type assignment both Value and Reference will be assigned i.e. all
instances will point to the single object.
• Value Type with Reference Type: This case and the last case to come are more interesting. I
used a structure in this particular scenario also. But this time it includes a Reference Type (A
Custom Class Object) Member besides a Value Type (An Integer) Member. When you
performing the assignments, it seems like a swallow copy, as Value Type member of first
instance won't effected, but the Reference Type member will alter according to the second
instance. So in this particular scenario, assignment of Reference Type member produced a
reference to a single object and assignment of Value Type member produced a local copy of
that member.
• Reference Type With Value Type : Contrary to the above case, in this scenario, both
Reference & Value Types will be affected. I.e. a Value Type member in a Reference Type will
be shared among its instances.
Here comes Serialization. You will serialize all your necessary business classes and save them
into a text or XML file, on your hard disk. So you can easily test your desired result by
comparing your serialized saved data with, your desired output data. You can say it is a little
bit of autonomic unit testing performed by the developer.
• Soap Serialization (Save your object data into binary format; mainly used in network
related communication).
https://github.com/kansiris/C-Sharp-c-interview-question 51/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Example:
In the above declaration the rows are fixed in size. But columns are not specified as they can
vary.
A single-threaded process contains only one thread while a multithreaded process contains
more than one thread for execution.
https://github.com/kansiris/C-Sharp-c-interview-question 52/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
System.Threading Namespace:
Like many other features, in .NET, System.Threading is the namespace that provides various
types to help in construction of multithreaded applications.
Type
Description
Thread
It represents a thread that executes within the CLR. Using this we can produce additional
threads in an application domain
Mutex
Monitor
Smaphore
It allows limiting the number of threads that can access a resource concurrently
Interlock
It provides atomic operations for variables that are shared by multiple threads
Threadpool
Thread
We can create anonymous types by using “new” keyword together with the object initializer.
Example:
var anonymousData = new
{ ForeName = "Jignesh",
SurName = "Trivedi" };
Console.WriteLine("First Name : " + anonymousData.ForeName);
https://github.com/kansiris/C-Sharp-c-interview-question 53/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Example:
If Any object collection having properties called FirstName , LastName, DOB etc.
and you want only FirstName and LastName after the Querying the data then.
class MyData
{
public string FirstName {get; set;}
public string LastName {get;. set;}
public DateTime DOB
{get; set;}
public string MiddleName {get; set; } }
static void Main(string[] args) {
// Create
Dummy Data to fill Collection.
List < MyData > data = new List < MyData > ();
data.Add(new MyData {FirstName = "Jignesh", LastName = "Trivedi", MiddleName = "G",
DOB = new DateTime(1990, 12, 30)});
data.Add(new MyData {FirstName = "Tejas", LastName
= "Trivedi", MiddleName = "G", DOB = new DateTime(1995, 11, 6) 64});
data.Add(new
MyData {FirstName = "Rakesh", LastName = "Trivedi", MiddleName = "G", DOB = new Date
Time(1993, 10, 8) });
data.Add(new MyData {FirstName = "Amit", LastName = "Vyas",
MiddleName = "P", DOB = newDateTime (1983, 6, 15)});
data.Add(new MyData {FirstName =
"Yash", LastName = "Pandiya", MiddleName = "K", DOB = newDateTime(1988, 7, 20)}); }
var
anonymousData = from pl in data
select new { pl.FirstName, pl.LastName };
foreach(var m in
anonymousData) {
Console.WriteLine("Name : " + m.FirstName + " " + m.LastName); } }
The Hashtable Collection: The Base Class libraries offers a Hashtable Class that is defined in
the System.Collections namespace, so you don't have to code your own hash tables. It
processes each key of the hash that you add every time and then uses the hash code to look
up the element very quickly. The capacity of a hash table is the number of elements the
hash table can hold. As elements are added to a hash table, the capacity is automatically
increased as required through reallocation. It is an older .Net Framework type.
Declaring a Hashtable: The Hashtable class is generally found in the namespace called
System.Collections. So to execute any of the examples, we have to add using
System.Collections; to the source code. The declaration for the Hashtable is:
Hashtable HT =
new Hashtable ();
LINQ stands for Language Integrated Query. LINQ is a data querying methodology which
provides querying capabilities to .NET languages with syntax similar to a SQL query
LINQ has a great power of querying on any source of data. The data source could be
collections of objects, database or XML files. We can easily retrieve data from any object
that implements the IEnumerable interface.
Advantages of LINQ:
• LINQ offers an object-based, language-integrated way to query over data no matter where
that data came from. So through LINQ we can query database, XML as well as collections.
• It allows you to query collections like arrays, enumerable classes etc. in the native
language of your application, and like VB or C# in much the same way as you would 66
query a database using SQL.
You can dynamically discover the set of interfaces supported by a given type using the
System.Reflection namespace. This namespace contains numerous related types as follows:
Types
Description
Assembly
https://github.com/kansiris/C-Sharp-c-interview-question 55/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Assemblyname
Eventinfo
Propertyinfo
Methodinfo
Reflection typically is used to dump out the loaded assemblies list, their reference to inspect
methods, properties etcetera.
Reflection is also used in the external disassembling tools
such Reflector, Fxcop and NUnit because .NET tools don't need to parse the source code
similar to C++.
Metadata Investigation:
The following program depicts the process of reflection by creating a console based
application. This program will display the details of the fields, methods, properties and
interfaces for any type within the mscorlib.dll assembly. Before proceeding, it is mandatory
to import "System.Reflection".
Here, we are defining a number of static methods in the program class to enumerate fields,
methods and interfaces in the specified type. The static method takes a single "System.Type"
parameter and returns void.
static void FieldInvestigation(Type t) {
Console.WriteLine("Fields");
FieldInfo[] fld = t.GetFields();
foreach(FieldInfo f in fld) {
Console.WriteLine("-->{0}", f.Name); } }
static void MethodInvestigation(Type t) {
Console.WriteLine("Methods");
MethodInfo[] mth = t.GetMethods();
foreach(MethodInfo m
in mth) { Console.WriteLine("-->{0}", m.Name); } }
https://github.com/kansiris/C-Sharp-c-interview-question 56/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Expression and Expression<> are basically classes that can represent the CSharp code as
Data. Unlike Func<> or Action<> Expressions are non-compiled Data about the code. Most
of LINQ Providers has been built using Expressions.
Walkthrough of a sample expression:
Expression can be parsed, analyzed in the program.
Let’s create a simple Expression:
// A
simple delegated operation which perform string join.
Func<string, string, string> StringJoin
= (str1, str2) => string.Concat(str1, str2);
Now I want to parse it analyze it or may be doing
some more but for that I need to treat this code as Data. Now let’s write an expression for
the above lambda expression:
Expression<Func<string, string, string>> StringJoinExpr =
(str1, str2) => string.Concat(str1, str 2);
The Expression Tree can be visualized as with its
major properties:
Let’s analyze our Expression according to above figure, and see what values are populated
to understand the break of Expression statement:
Var
• Var was introduced with C# 3.0
• It can store any type of value but It is mandatory to
initialize var types at the time of declaration.
• It is type safe i.e. Compiler has all information
about the stored value, so that it doesn't cause any issue at run-time.
• Var type cannot be
passed as method argument and method cannot return object type. Var type work in the
scope where it defined.
• No need to cast because compiler has all information to perform
operations.
• Doesn't cause problem because compiler has all information about stored
value.
• Useful when we don’t know actual type i.e. type is anonymous.
Dynamic
• Dynamic was introduced with C# 4.0
• It can store any type of the variable, similar
to old VB language variable.
• It is not type safe i.e. Compiler doesn't have any information
about the type of variable.
• Dynamic type can be passed as method argument and method
also can return dynamic type.
• Casting is not required but you need to know the properties
and methods related to stored type.
• Cause problem if the wrong properties or methods
are accessed because all the information about stored value is get resolve only at run time.
•
Useful when we need to code using reflection or dynamic languages or with the COM
objects, because you need to write less code.
https://github.com/kansiris/C-Sharp-c-interview-question 57/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
An object can be considered a "thing" that can perform a set of related activities. The set of
activities that the object performs defines the object's behavior. For example, the hand can
grip something or aStudent (object) can give the name or address. In pure OOP terms an
object is an instance of a class
According to the above sample we can say that Student object, named objstudent, has
created out of the student class.
In real world you will often find many individual objects all of the same kind. As an example,
there may be thousands of other bicycles
in existence, all of the same make and model.
Each bicycle has built from the same blueprint. In object-oriented terms, we say that the
bicycle is an instance of the class of objects known as bicycles. In the software world, though
you may not have realized it, you have already used classes. For example, the Textbox
control, you always used, is made out of the Textbox class, which defines its appearance and
capabilities. Each time you drag a Textbox control, you are actually creating a new instance
of the Textbox class.
Encapsulation:
Encapsulation is a process of binding the data members and member
functions into a single unit.
Example for encapsulation is class. A class can contain data
structures and methods.
Consider the following class
public class Aperture
{public Aperture
()
{ }
In this example we encapsulate some data such as height, width, thickness and method Get
Volume. Other methods or objects can interact with this object through methods that have
public access modifier
Abstraction:
https://github.com/kansiris/C-Sharp-c-interview-question 58/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Abstraction is a process of hiding the implementation details and displaying the essential
features.
Example1: A Laptop consists of many things such as processor, motherboard, RAM,
keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use
it, you don't need to know how internally LCD screens, keyboard, web camera, battery,
wireless antenna, speaker’s works. You just need to know how to operate the laptop by
switching it on. Think about if you would have to call to the engineer who knows all internal
details of the laptop before operating it. This would have highly expensive as well as not
easy to use everywhere by everyone.
Now lets try to copy the same code inside Main method and try to compile
[STAThread]
static void Main()
{ //Access specifiers comes into picture only when you create object of
class outside the class
Class1 obj = new Class1();
// obj.i =10; //Error can’t access private
data through object.
obj.j =10;
// obj.k=10; //Error can’t access protected data through
object.
obj.m=10;
obj.n=10;
// obj.s =10; //Errror Static data can be accessed by class names
only
Class1.x = 10; //Error can’t access private data outside class
// obj.y = 10; //Errror Static
data can be accessed by class names only
Class1.y = 10;
}
https://github.com/kansiris/C-Sharp-c-interview-question 59/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
[STAThread]
static void Main()
{
//Access specifiers comes into picture only when you create
object of class outside the class
Class1 obj = new Class1();
// obj.i =10; //Error can’t access
private data through object.
obj.j =10;
// obj.k=10; //Error can’t access protected data
through object.
// obj.m=10; // Error can’t access internal data outside assembly
//
obj.n=10; // Error can’t access internal data outside assembly
// obj.s =10; //Errror Static
data can be accessed by class names only
Class1.x = 10; //Error can’t access private data
outside class
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y
= 10;
}
Abstraction is a process that involves identifying the critical behavior of an object and
eliminating irrelevant and complex details.
Inheritance:
Inheritance is a process of deriving the new class from already existing class
C# is a
complete object oriented programming language. Inheritance is one of the primary
concepts of object-oriented programming. It allows you to reuse existing code. Through
effective use of inheritance, you can save lot of time in your programming and also reduce
errors, which in turn will increase the quality of work and productivity. A simple example to
understand inheritance in C#.
Using System;
Public class BaseClass
{ Public BaseClass ()
{ Console.WriteLine ("Base Class
Constructor executed"); }
Public void Write ()
{ Console.WriteLine ("Write method in Base
Class executed"); }
}
CC.Write ();
}}
In the Main () method in ChildClass we create an instance of childclass. Then we call the
write () method. If you observe the ChildClass does not have a write() method in it. This write
() method has been inherited from the parent BaseClass.
The output of the above program
is
Output:
Base Class Constructor executed
Child Class Constructor executed
Write method in
Base Class executed
This output proves that when we create an instance of a child class, the base class
constructor will automatically be called before the child class constructor. So in general Base
classes are automatically instantiated before derived classes.
https://github.com/kansiris/C-Sharp-c-interview-question 60/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The
base class is specified by adding a colon, ":", after the derived class identifier and then
specifying the base class name.
C# supports single class inheritance only. What this means is, your class can inherit from
only one base class at a time. In the code snippet below, class C is trying to inherit from
Class A and B at the same time. This is not allowed in C#. This will lead to a compile time
error: Class 'C' cannot have multiple base classes: 'A' and 'B'.
public class A
{ }
public class B
{ }
public class C : A, B
{ }
Note: Classes can inherit from multiple interfaces at the same time.
Using System;
Public class A
{Public void M1 ()
{ }
Private void M2 ()
{ }}
Public class B: A
{Public static void Main ()
{B B1 = new B ();
B1.M1 ();
//Error, Cannot access
private member M2
//B1.M2 ();
}}
https://github.com/kansiris/C-Sharp-c-interview-question 61/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Method Hiding and Inheritance We will look at an example of how to hide a method in C#.
The Parent class has a write () method which is available to the child class. In the child class I
have created a new write () method. So, now if I create an instance of child class and call the
write () method, the child class write () method will be called. The child class is hiding the
base class write () method.
If we want to call the parent class write () method, we would have to type cast the child
object to Parent type and then call the write () method as shown in the code snippet below.
Using System;
Public class Parent
{ Public void Write ()
{ Console.WriteLine ("Parent Class
write method"); }}
Polymorphism:
• It allows you to invoke methods of derived class through base class reference during
runtime.
• It has the ability for classes to provide different implementations of methods that are
called through the same name.
2. Runtime polymorphism/Overriding
Compile time polymorphism is method and operators overloading. It is also called early
binding.
In method overloading method performs the different task at the different input
parameters.
Runtime time polymorphism is done using inheritance and virtual functions. Method
overriding is called runtime polymorphism. It is also
called late binding.
https://github.com/kansiris/C-Sharp-c-interview-question 62/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
When overriding a method, you change the behavior of the method for the derived class.
Overloading a method simply involves having
another method with the same prototype.
Caution: Don't confused method overloading with method overriding, they are different,
unrelated concepts. But they sound similar.
using System;
namespace method_overloading
{ class Program
{ public class Print
{ public
void display(string name)
{ Console.WriteLine ("Your name is : " + name); }
public void
display(int age, float marks)
{ Console.WriteLine ("Your age is : " + age);
Console.WriteLine
("Your marks are :" + marks);
} }
static void Main(string[] args)
{ Print obj = new Print ();
obj.display ("George");
obj.display (34, 76.50f);
Console.ReadLine ();
} }}
Note: In the code if you observe display method is called two times. Display method will
work according to the number of parameters and type of parameters.
You should consider overloading a method when you for some reason need a couple of
methods that take different parameters, but conceptually do the same thing. Method
overloading showing many forms.
using System;
namespace method_overloading_polymorphism
{ Class Program
{ Public class
Shape
{ Public void Area (float r)
{ float a = (float)3.14 * r;
// here we have used function
overload with 1 parameter.
Console.WriteLine ("Area of a circle: {0}",a);
}
Public void
Area(float l, float b)
{ float x = (float)l* b;
// here we have used function overload with 2
parameters.
Console.WriteLine ("Area of a rectangle: {0}",x);
}
public void Area(float a, float b,
float c)
{ float s = (float)(abc)/2;
// here we have used function overload with 3 parameters.
Console.WriteLine ("Area of a circle: {0}", s);
} }
Static void Main (string[] args)
{ Shape ob =
new Shape ();
ob.Area(2.0f); ob.Area(20.0f,30.0f);
ob.Area(2.0f,3.0f,4.0f);
Console.ReadLine (); }
}}
https://github.com/kansiris/C-Sharp-c-interview-question 63/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Things to keep in mind while method overloading If you use overload for method, there are
couple of restrictions that the compiler imposes. The rule is that overloads must be different
in their signature, which means the name and the number and type of parameters. There is
no limit to how many overload of a method you can have. You simply declare them in a
class, just as if they were different methods that happened to have the same name.
Method Overriding:
Whereas Overriding means changing the functionality of a method without changing the
signature. We can override a function in base class by creating a similar function in derived
class. This is done by using virtual/overrides keywords. Base class method has to be marked
with virtual keyword and we can override it in derived class using override keyword. Derived
class method will completely overrides base class method i.e. when we refer base class
object created by casting derived class object a method in derived class will be called.
Example:
// Base class
public class BaseClass
{public virtual void Method1()
{Console.Write("Base Class Method");}}
// Derived class
public class DerivedClass : BaseClass
{public override void Method1()
{Console.Write("Derived Class Method"); }}
// Using base
and derived class
public class Sample
{public void TestMethod()
{// calling the overriden
method
DerivedClass objDC = new DerivedClass();
objDC.Method1();
// calling the baesd
class method
BaseClass objBC = (BaseClass)objDC;
objDC.Method1();}}
Output:
Classes have complicated internal structures, including data and functions, object
initialization and cleanup for classes is much more complicated than it is for simple data
structures. Constructors and destructors are special member functions of classes that are
used to construct and destroy class objects. Construction may involve memory allocation
and initialization for objects.
Constructors and destructors obey the same access rules as member functions. For example,
if you declare a constructor with protected access, only derived classes and friends can use
it to create class objects.
https://github.com/kansiris/C-Sharp-c-interview-question 64/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
The compiler automatically calls constructors when defining class objects and calls
destructors when class objects go out of scope. A constructor does not allocate memory for
the class object it’s this pointer refers to, but may allocate storage for more objects than its
class object refers to. If memory allocation is required for objects, constructors can explicitly
call the new operator. During cleanup, a destructor may release objects allocated by the
corresponding constructor. To release objects, use the delete operator.
Example of Constructor
class C
{ private int x;
private int y;
public C (int i, int j)
{ x = i; y = j; }
public void display ()
Example of Destructor
class D
{ public D ()
{ // constructor }
~D ()
{ // Destructor } }
Note: The variable value may be changed, but the original immutable data value was
discarded and a new data value was created in memory.
https://github.com/kansiris/C-Sharp-c-interview-question 65/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
No.
Question : How can you sort the elements of the array in descending
order?
By calling Sort() and then Reverse() methods.
Question : Will the finally block get executed if an exception has not
occurred?
Yes.
https://github.com/kansiris/C-Sharp-c-interview-question 66/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Presentation (UI), Business (logic and underlying code) and Data (from storage or other
sources).
Question : Can you prevent your class from being inherited by another
class?
Yes. The keyword “sealed” will prevent the class from being inherited.
Question : Why can’t you specify the accessibility modifier for methods
inside the interface?
They all must be public, and are therefore public by default.
Question : What’s the implicit name of the parameter that gets passed
into the set method/property of a class?
https://github.com/kansiris/C-Sharp-c-interview-question 67/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Value. The data type of the value parameter is defined by whatever data type the property is
declared .
Question : What’s the implicit name of the parameter that gets passed
into the class’ set method?
Value, and it’s datatype depends on whatever variable we’re changing.
https://github.com/kansiris/C-Sharp-c-interview-question 68/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Question : What’s the top .NET class that everything is derived from?
System.Object.
Question : Can you declare the override method static while the
original method is non-static?
No, you can’t, the signature of the virtual method must remain the same, only the keyword
virtual is changed to keyword override.
Question : Why can’t you specify the accessibility modifier for methods
inside the interface?
They all must be public. Therefore, to prevent you from getting the false impression that
you have any freedom of choice, you are not allowed to specify any accessibility, it’s public
by default.
https://github.com/kansiris/C-Sharp-c-interview-question 69/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
O/p is 0 because the range of byte is 0-255 so if the range is exceeded then the b value will
round to 0 but this type of programming is not safe type it is unsafe
if we want to display error message instead of 0 then we have to go for checked block
Ex: Checked
{ byte b=254;
b++; b++;
Console.WriteLine(b);
}
https://github.com/kansiris/C-Sharp-c-interview-question 70/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
o/p:Arthimetic overflow Error will occur unchecked block:it is used to disable overflow
checking for arthimetic and conversion functions
Ex: unChecked
{ byte b=254;
b++; b++;
Console.WriteLine(b);
output:0
Console.WriteLine(byte.MaxValue);
Ex:int to long
Ex:long to int
VisualStudioTools---->VisualStudioCommandPrompt---->type ILDASM.exe
https://github.com/kansiris/C-Sharp-c-interview-question 71/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Question : How to Call the Default constructor of one class with the
parameterised constructor of same class?
by using this()
https://github.com/kansiris/C-Sharp-c-interview-question 73/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
EventHandlers
1. when were we have declared instance variable and local variable with the same class,
with in the method control will give the priority for variable to overcome that we have
to access the instance variables with the help of ”this” keyword
o/p ERROR:- because local variable we should initialized with some value before accessing.
C# programs
Question: C# program to print prime numbers
A prime number is not divisible by any other number apart from 1 and itself. So, we use this
logic in this program to determine if a number is prime.
https://github.com/kansiris/C-Sharp-c-interview-question 74/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
using System;
namespace SamplePrograms
{ class PrimeNumber
{ public static void Main()
{
// Declare a boolean variable to determine is if a number is prime
bool isNumberComposite
= false;
int j;
// Prompt the user to enter their target number
Console.WriteLine("Enter your
Target?");
// Read the target number and convert to integer
int target =
Int32.Parse(Console.ReadLine());
// 1 is neither prime nor composite. So start at 2
for (int i =
2; i <= target; i++)
1. Start at Zero. Increment the value by 2, print it. Do this until you reach your target
number.
2. Start at Zero. Divide the number by 2. If the remainder is zero, then you know the
number is even. So print it and then increment it by 1 and divide the number by 2
again. Repeat this until we reach our target number.
This program can also be used to
print odd numbers by making a minor logic change. Initialize the targetNumber
variable to 1 instead of 0. If you are using dividing logic, then print the number if the
remainder is not zero.
Note: This program will crash and throws an exception, if you enter a very big number or a
string. To handle exceptions, we can make use of try catch blocks. We will look at this in
another program.
using System;
namespace SamplePrograms
{ class EvenNumbers
{ public static void Main()
{
// Prompt the user to enter a target number. Target number is the
// number untill which
the user want to have even and odd numbers printed
Console.WriteLine("Please enter your
target");
// Declare a variable to hold the target number
int targetNumber = 0;
// Retrieve,
Convert and store the target number
targetNumber = Convert.ToInt32(Console.ReadLine());
// Use a FOR or WHILE loop to print the even numbers, until our target number
for (int i = 0;
i <= targetNumber; i = i + 2)
{ Console.WriteLine(i);}
// You can also check if a number is
even, by dividing it by 2.
//for (int i = 0; i <= targetNumber; i++)
//{ if ((i % 2) == 0) {
Console.WriteLine(i); }}
// You can also use a while loop to do the same as shown below.
//int start = 0;
//while (start <= targetNumber)
//{ Console.WriteLine(start); start = start + 2;
}
// This line is to make the program wait for user input, instead of immediately closing
Console.ReadLine();
} } }
https://github.com/kansiris/C-Sharp-c-interview-question 75/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Let's see the palindrome program in C#. In this program, we will get an input from the user
and check whether number is palindrome or not.
using System;
Output:
Number is Palindrome.
https://github.com/kansiris/C-Sharp-c-interview-question 76/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Before going to write the C# program to check whether the number is Armstrong or not,
let's understand what is Armstrong number.
Armstrong number is a number that is equal to
the sum of cubes of its digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong
numbers.
1. 371 = (333)+(777)+(111)
2. where:
3. (333)=27
4. (777)=343
5. (111)=1
6. So:
7. 27+343+1=371
using System;
n= int.Parse(Console.ReadLine()); temp=n;
n=n/10; }
Output:
https://github.com/kansiris/C-Sharp-c-interview-question 77/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
We can reverse a number in C# using loop and arithmetic operators. In this program, we are
getting number as input from the user and reversing that number.
Let's see a simple C#
example to reverse a given number.
using System;
n= int.Parse(Console.ReadLine());
while(n!=0)
}
}
Output:
{ int a=0,b=1,i,c,n,j;
Console.Write("Enter the limit: ");
n= int.Parse(Console.ReadLine());
a=0;
b=1;
Console.Write(b+"\t");
c=a+b;
Console.Write(c+"\t");
a=b;
b=c;
Console.Write("\n");
}
}
}
https://github.com/kansiris/C-Sharp-c-interview-question 78/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
n= int.Parse(Console.ReadLine()); while(n>0)
}//end of switch
n=n/10;
}//end of while loop
Output:
Enter the Number= 357546
three five seven five four six
https://github.com/kansiris/C-Sharp-c-interview-question 79/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Like alphabet triangle, we can write the C# program to print the number triangle. The
number triangle can be printed in different ways.
Let's see the C# example to print number
triangle.
using System;
{ int i,j,k,l,n;
{ Console.Write(" "); }
for(k=1;k<=i;k++)
{ Console.Write(k); }
for(l=i-1;l>=1;l--)
{ Console.Write(l); }
Console.Write("\n");
} } }
Output:
Enter the Range=5
1
121
12321
1234321
123454321
1. By + and -
2. By * and /
Let's see a simple C# example to swap two numbers without using third variable.
using System;
}
}
Output:
Before swap a= 5 b= 10
After swap a= 10 b= 5
https://github.com/kansiris/C-Sharp-c-interview-question 80/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
}}
Output:
Before swap a= 5 b= 10
After swap a= 10 b= 5
Step 3: Repeat the step 2 until the number is greater than zero
{
public static void Main(string[] args)
{ int n, i;
n= int.Parse(Console.ReadLine());
{ a[i]=n%2; n= n/2; }
{ Console.Write(a[i]);
}
}
}
Output:
https://github.com/kansiris/C-Sharp-c-interview-question 81/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
In C# language, we can easily convert number in characters by the help of loop and switch
case. In this program, we are taking input from the user and iterating this number until it is
0. While iteration, we are dividing it by 10 and the remainder is passed in switch case to get
the word for the number.
using System;
{ int n,sum=0,r;
n= int.Parse(Console.ReadLine());
while(n>0)
n=sum;
while(n>0)
{ r=n%10;
switch(r)
}//end of switch
n=n/10;
}//end of while loop
}}
Output:
https://github.com/kansiris/C-Sharp-c-interview-question 82/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
using System;
namespace SamplePrograms
{ class NumberTable
{ public static void Main()
{
// Prompt the user to enter number for multiplication table
Console.WriteLine("For which
number do you want to print multiplication table");
// Read the number from console and
convert to integer
int Number = Convert.ToInt32(Console.ReadLine());
// Prompt the user for
multiplication table target
Console.WriteLine("What is your target? 10, 20, 30 etc...");
// Read
the target from console and convert to integer
int Target =
Convert.ToInt32(Console.ReadLine());
// Loop to print multiplication table until we reach the
target
for (int i = 1; i <= Target; i++)
{ // Compute multiplication result
int Result = Number
* i;
// Format and Print the multiplication table
Console.WriteLine(Number.ToString() + " X "
+ i.ToString() +
" = " + Result.ToString());
// The above line can also be rewritten as shown
below.
// Console.WriteLine("{0} X {1} = {2}", Number, i, Result);
}
}
}
}
using System;
namespace SamplePrograms
{ class Alphabets
{ public static void Main()
{ //
Loop from a thru z (lower case alphabets)
for (char alphabet = 'a'; alphabet <= 'z';
alphabet++)
{ Console.Write(alphabet + " "); }
//Another way to print lower case alphabets
//for (int i = 0; i < 26; i++)
//{ Console.Write(Convert.ToChar(i + (int)'a') + " "); }
Console.WriteLine();
// Loop from A thru Z (upper case alphabets)
for (char alphabet = 'A';
alphabet <= 'Z'; alphabet++)
{ Console.Write(alphabet + " "); }
//Another way to print
uppercase case alphabets
//for (int i = 0; i < 26; i++)
//{ Console.Write(Convert.ToChar(i +
(int)'A') + " "); }
Console.ReadLine();
}
}
}
https://github.com/kansiris/C-Sharp-c-interview-question 83/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
using System;
namespace SamplePrograms
{ class PowerFunction
{ public static void Main()
{
// Prompt the user to enter base
Console.WriteLine("Enter your base");
int Base =
Convert.ToInt32(Console.ReadLine());
// Prompt the user to enter exponent
Console.WriteLine("Enter your exponent");
int Exponent =
Convert.ToInt32(Console.ReadLine());
// Call the power method passing it Base and Exponent
int Result = Power(Base, Exponent);
// In System.Math class there is Pow() static method
which is
// very similar to the static Power() method we implemented
// double Result =
System.Math.Pow(Base, Exponent);
// Print the result
Console.WriteLine("Result = {0}",
Result);
}
public static int Power(int Base, int Exponent)
{ // Declare a variable to hold the
result
int Result = 1;
// Multiply the Base number with itself, for
// exponent number of
times
for (int i = 1; i <= Exponent; i++)
{ Result = Result * Base; }
//return the Result
return
Result;
}
}
}
using System;
using System.Linq;
namespace SamplePrograms
{ class CountEmailsByDomain
{ public static void Main()
{ // User List of emails seperated by semi colon. You can have as
many
// number of emails you want in this string.
string UserInputEmails =
"aa@xyz.com;cc@abc.com;bb@abc.com;dd@abc.com";
// Split the string into a string array.
string[] UserEmails = UserInputEmails.Split(';');
// Select only the domain part of the emails
into a string array, using substring() function
string[] EmailsDomain = UserEmails.Select(x =>
x.Substring(x.LastIndexOf("@") + 1)).ToArray();
// Group the emails by email domain, and
select the Domain and respective count
var Result = EmailsDomain.GroupBy(x => x).Select(y
=> new { Domain = y.Key, Count = y.Count() });
// Finally print the domain name and the
emails count
foreach (var obj in Result)
{ Console.WriteLine("Domain = {0} & Count =
{1}",obj.Domain, obj.Count);
}
}
}
}
Build a simple calculator using c# programming language. The calculator should have the
following features.
1. Adding 2 Numbers
2. Subtracting 2 Numbers
3. Multiplying 2 Numbers
4. Dividing 2 Numbers
Also, the program should run as long as the user wants it to be running.
https://github.com/kansiris/C-Sharp-c-interview-question 84/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
using System;
namespace SamplePrograms
{ class SimpleCalculator
{ public static void
Main()
{ string UserSelection = string.Empty;
do
{ PrintMenu();
int UserChoice =
Convert.ToInt32(Console.ReadLine());
while (UserChoice < 1 || UserChoice > 4)
{
Console.WriteLine("Invalid Option. Try again");
PrintMenu(); Console.WriteLine();
UserChoice
= Convert.ToInt32(Console.ReadLine());
}
Calculate(UserChoice);
Console.WriteLine("Do you
want to continue");
UserSelection = Console.ReadLine();
while (UserSelection.ToUpper() !=
"NO" &&
UserSelection.ToUpper() != "YES")
{ Console.WriteLine();
Console.WriteLine("Invalid
Input - Please type YES or NO");
Console.WriteLine("Do you want to continue");
UserSelection = Console.ReadLine();
} }
while (UserSelection.ToUpper() != "NO");
Console.WriteLine();
Console.WriteLine("The program will now terminate");
}
public static
void PrintMenu()
{ Console.WriteLine();
Console.WriteLine("Select your option");
Console.WriteLine("------------------");
Console.WriteLine("1. Addition");
Console.WriteLine("2. Subtraction");
Console.WriteLine("3. Multiplication");
Console.WriteLine("4. Division");
Console.WriteLine();
}
public static void Calculate(int
SelectedOption)
{ int Result = 0;
Console.WriteLine("Enter your first number");
int
FirstNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your second
number");
int SecondNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
switch (SelectedOption)
{ case 1:
Result = FirstNumber + SecondNumber;
Console.WriteLine("{0} + {1} = {2}", FirstNumber, SecondNumber, Result);
break;
case 2:
Result = FirstNumber - SecondNumber;
Console.WriteLine("{0} - {1} = {2}", FirstNumber,
SecondNumber, Result);
break;
case 3:
Result = FirstNumber * SecondNumber;
Console.WriteLine("{0} * {1} = {2}", FirstNumber, SecondNumber, Result);
break;
case 4:
Result = FirstNumber / SecondNumber;
Console.WriteLine("{0} / {1} = {2}", FirstNumber,
SecondNumber, Result);
break;
}
}
}
}
}
}
https://github.com/kansiris/C-Sharp-c-interview-question 85/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Write a c# program that inserts a single space before every upper case letter. For example, if
I have string like "ProductUnitPrice", the program should convert it to "Product Unit Price".
Usually database column names will not have spaces, but when you display them to the
user, it makes sense to have spaces.
using System;
using System.Text;
namespace SamplePrograms
{ class
SpaceBeforeUpperCaseLetter
{ public static void Main()
{ // Prompt the user for input
Console.WriteLine("Please enter your string");
// Read the input from the console
string
UserInput = Console.ReadLine();
// Convert the input string into character array
char[]
arrUserInput = UserInput.ToCharArray();
// Initialize a string builder object for the output
StringBuilder sbOutPut = new StringBuilder();
// Loop thru each character in the string array
foreach (char character in arrUserInput)
{ // If the character is in uppercase
if
(char.IsUpper(character))
{ // Append space
sbOutPut.Append(" "); }
// Append every
charcter to reform the output
sbOutPut.Append(character); }
// Remove the space at the
begining of the string
sbOutPut.Remove(0, 1);
// Print the output
Console.WriteLine(sbOutPut.ToString());
Console.ReadLine();
} } }
1. If the user enters "Ten" instead of 10, the program should let the user know only
numbers can be added.
2. If the user, enters a very large number, the program should let the user know about the
range allowed.
using System;
namespace SamplePrograms
{ class
ExceptionHandlingAtItsBest
{ public static void Main()
{ string strUserChoice =
String.Empty;
do
{ try
{ Console.WriteLine("Please enter first number");
int FN =
Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter second number");
int SN = Convert.ToInt32(Console.ReadLine());
int Total = FN + SN;
Console.WriteLine("Total = {0}", Total);
}
catch (FormatException)
{
Console.WriteLine("Invalid Input. Only numbers please."); }
catch (OverflowException)
{
Console.WriteLine("Only numbers between {0} and {1} are allowed",
Int32.MinValue,
Int32.MaxValue); }
catch (Exception)
{ Console.WriteLine("Unknown problem, please
contact administrator"); }
do
{ Console.WriteLine("Do you want to continue - Yes or
No");
strUserChoice = Console.ReadLine();
}
while (strUserChoice.ToUpper() != "YES" &&
strUserChoice.ToUpper() != "NO");
}
while (strUserChoice.ToUpper() != "NO");
} } }
https://github.com/kansiris/C-Sharp-c-interview-question 87/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
I want a c# program that can find and print, the smallest and largest number in a given
integer array.
using System;
using System.Linq;
namespace SamplePrograms
{ class
LargestSmallest
{ public static void Main()
{ // Declare and initialize the integer array
int[]
NumbersArray = { 102, 34, 89, 12, 187, 29, 111};
// Sort the array, first element in the array
will be
// smallest and the last element will be largest
Array.Sort(NumbersArray);
// Print the
smallest number in the array
Console.WriteLine("Samllest Number = {0}", NumbersArray[0]);
// Print the largest number in the array.
Console.WriteLine("Largest Number = {0}",
NumbersArray[NumbersArray.Length -1]);
// Linq makes this much easier, as we have Min()
and Max() extension methods
// Console.WriteLine("Samllest Number = {0}",
NumbersArray.Min());
// Console.WriteLine("Largest Number = {0}", NumbersArray.Max());
} }
}
C# Program below shows how to compute factorial for a given number. If you like this
artcile, please click g+1 button below to share with your friends.
using System;
namespace SamplePrograms
{ class Factorial
{ public static void Main()
{ //
Prompt the user to enter their target number to calculate factorial
Console.WriteLine("Please
enter the number for which you want to compute factorial");
try
{ // Read the input from
console and convert to integer data type
int iTargetNumber =
Convert.ToInt32(Console.ReadLine());
// Factorial of Zero is 1
if (iTargetNumber == 0)
{
Console.WriteLine("Factorial of Zero = 1"); }
// Compute factorial only for non negative
numbers
else if (iTargetNumber < 0)
{ Console.WriteLine("Please enter a positive number
greater than 1"); }
// If the number is non zero and non negative
else
{ // Declare a variable
to hold the factorial result.
double dFactorialResult = 1;
// Use for loop to calcualte factorial
of the target number
for (int i = iTargetNumber; i >= 1; i--)
{ dFactorialResult =
dFactorialResult * i; }
// Output the result to the console
Console.WriteLine("Factorial of {0} =
{1}", iTargetNumber, dFactorialResult);
} }
catch (FormatException)
{ // We get format
exception if user enters a word instead of number
Console.WriteLine("Please enter a valid
number", Int32.MaxValue); }
catch (OverflowException)
{ // We get overflow exception if user
enters a very big number,
// which a variable of type Int32 cannot hold
Console.WriteLine("Please enter a number between 1 and {0}", Int32.MaxValue); }
catch
(Exception)
{ // Any other unforeseen error
Console.WriteLine("There is a problem! Please try
later");
}
}
}
}
https://github.com/kansiris/C-Sharp-c-interview-question 88/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
For example, please refer to the sample input and output below.
Input Output
1 0
1.0 0
1.1 1
1.12 2
1.123 3
1.1100 2
1.010 2
1.001100 4
using System;
namespace SampleProgram
{ class MainProgram
{ public static void
Main(string[] args)
{ // Create the decimal array for sample test data
decimal[]
decimalNumbers = { 1, 1.0M, 1.1M, 1.12M, 1.123M, 1.1100M, 1.010M, 1.001100M };
// Loop
thru each decimal number
foreach (decimal decimalNumber in decimalNumbers)
{ // Print
the original number and total decimal places
Console.WriteLine("Original Decimal Number
= {0}, Total Decimal Places = {1}",
decimalNumber, GetDecimalPartCount(decimalNumber));
}
}
// Function that return the total decimal places
private static int
GetDecimalPartCount(decimal decimalNumber)
{ // Dividing decimal number with 1 gives
the decimal part
decimal decimalPlaces = decimalNumber % 1;
if (decimalPlaces != 0)
{ //
Get the index of dot from the decimal part
int indexOfDot =
decimalPlaces.ToString().IndexOf('.');
// Use the 0.######## format string to rip off trailing
zeros, and get the count
int numberOfDecimals =
decimalPlaces.ToString("0.##########").Substring(indexOfDot).Length - 1;
return
numberOfDecimals;
}
// Finally convert decimal to int and return
return (int)decimalPlaces;
}
using System;
namespace SampleProgram
{ class MainProgram
{ public static void
Main(string[] args)
{ decimal[] decimalNumbers = { 1.0M, 1.01M, 1.0010M, 0.00M, 1.0050M};
foreach (decimal decimalNumber in decimalNumbers)
{ Console.WriteLine("Original Decimal
Number = {0}, Without Zeros = {1}",
decimalNumber, decimalNumber.ToString("0.####"));
If I enter 1.1234567890, we get 1.1235, instead of 1.123456789. This is because, the number
of # symbols in the ToString("0.####") is only 4. The maximum decimal places, you want in
the output is represented by the # symbol. In general a C# decimal datatype can have 29
total number of digits. This includes both integral and decimal part of a decimal.
https://github.com/kansiris/C-Sharp-c-interview-question 89/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
Releases
No releases published
Packages
https://github.com/kansiris/C-Sharp-c-interview-question 90/91
21/09/2021, 12:49 GitHub - kansiris/C-Sharp-c-interview-question: List of top 500 C# csharp Interview Questions & Answers....Coding exercise…
No packages published
https://github.com/kansiris/C-Sharp-c-interview-question 91/91