What is Method Hiding
in C#?
If the derived class doesn't want to use methods in the base class,
derived class can implement it's own version of the same method with same
signature. For example, in the classes given below, DriveType() is implemented
in the derived class with same signature. This is called Method Hiding.
class Car
{
public void
DriveType()
{
Console.WriteLine("Right Hand Drive");
}
}
class Ford :
Car
{
public void
DriveType()
{
Console.WriteLine("Right Hand ");
}
}
What is Abstract Class
in C#?
If we don't want a class to be instantiated, define the class as
abstract. An abstract class can have abstract and non-abstract classes. If a
method is defined as abstract, it must be implemented in derived class. For
example, in the classes given below, method Drive Type is defined as
abstract.
abstract class Car
{
public Car()
{
Console.WriteLine("Base Class Car");
}
public
abstract void DriveType();
}
class Ford :
Car
{
public void
DriveType()
{
Console.WriteLine("Right Hand ");
}
}
Method DriveType
get implemented in derived class.
What is a Constructor in C#?
Constructor is a special method that gets invoked/called automatically,
whenever an object of a given class gets instantiated. In our class car,
constructor is defined as shown below
public Car()
{
Console.WriteLine("Base Class Car");
}
Whenever an instance of class car is created from the same class or it’s
derived class (Except Few Scenarios), Constructor get called and sequence of
code written in the constructor get executed.
interface Breaks
{
void BreakType();
}
interface Wheels
{
void WheelType();
}
class Ford : Breaks, Wheels
{
public Ford()
{
Console.WriteLine("Derived Class Ford");
}
public void Price()
{
Console.WriteLine("Ford Price : 100K $");
}
public void BreakType()
{
Console.WriteLine("Power Break");
}
public void WheelType()
{
Console.WriteLine("Bridgestone");
}
}
What
is Delegate? And types of Delegates?
Delegate is an abstract pointer to a function or method. In other words
you can create a pointer which points to a method or function and then pass
that pointer wherever you wish and invoke the function/method.
Delegates are used in the following cases:
Delegates can be used to handle (call/invoke) multiple methods on a
single event.
Delegates can be used to define callback (asynchronous) methods.
Delegates can be used for decoupling and implementing generic behaviors.
Delegates can be invoked method at runtime.
Delegates can be used in LINQ for parsing the Expression Tree.
Delegates can be used in different Design Pattern.
Types of Delegates
There are three types of delegates that can be used in C#.
1)Single Delegate
2)Multicast Delegate
3)Generic Delegate
1. Func
2. Action
3. Predicate
Can we use delegates for asynchronous method calls in C#?
Yes. We can use delegates
for asynchronous method calls.
What are the uses of
delegates in C#?
Below are the lists
of uses of delegates in C# -
·
Callback Mechanism
· Asynchronous
Processing
· Abstract
and Encapsulate method
· Multicasting
Define Multicast
Delegate in C#?
A delegate with
multiple handlers are called as multicast delegate. The example to demonstrate
the same is given below
public delegate
void CalculateMyNumbers(int x, int y);
int x = 6;
int y = 7;
CalculateMyNumbers
addMyNumbers = new CalculateMyNumbers(FuncForAddingNumbers);
CalculateMyNumbers
multiplyMyNumbers = new CalculateMyNumbers(FuncForMultiplyingNumbers);
CalculateMyNumbers
multiCast = (CalculateMyNumbers)Delegate.Combine (addMyNumbers,
multiplyMyNumbers);
multicast.Invoke(a,b);
What are the
differences between events and delegates in C#?
Main difference
between event and delegate is event will provide one more of encapsulation over
delegates. So when you are using events destination will listen to it but
delegates are naked, which works in subscriber/destination model.
What is nested class?
A Nested classes are classes within classes.
A nested class is any class whose declaration occurs within the body of
another class or interface.
What
is a base class?
A class declaration may specify a base class by following the class name
with a colon and the name of the base class. Omitting a base class
specification is the same as deriving from type object.
Where
are the types of arrays in C#?
· Single-Dimensional.
· Multidimensional.
· Jagged
arrays.
What
is Jagged Arrays?
The array which has elements of type array is called jagged array. The
elements can be of different dimensions and sizes. We can also call jagged
array as Array of arrays.
(or)
A jagged array is an array whose elements are arrays.
The elements of a jagged array can be of different dimensions and sizes.
A jagged array is sometimes called an array–of–arrays.
What is the difference
between methods – “System.Array.Clone()” and “System.Array.CopyTo()” in C#?
“CopyTo()” method
can be used to copy the elements of one array to other.
“Clone()” method is
used to create a new array to contain all the elements which are in the
original array.
Explain sealed class in
C#?
Sealed class is
used to prevent the class from being inherited from other classes. So “sealed”
modifier also can be used with methods to avoid the methods to override in the
child classes.
Give an example of
using sealed class in C#?
Below is the sample
code of sealed class in C# -
Class X {}
Sealed class Y: X
{}
Sealed Methods-
Class A
{
Protected virtual
void First () { }
Protected
virtual void second () { }
}
Class B: A
{
Sealed protected
override void First () {}
Protected
override void second () { }
}
If any class
inherits from class “B” then method – “First” will not be overridable as this
method is sealed in class B.
How the exception
handling is done in C#?
In C# there is a “try…
catch” block to handle the error.
Can we execute multiple
catch blocks in C#?
No. Once any
exception is occurred it executes specific exception catch block and the
control comes out.
Can we have only “try”
block without “catch” block in C#?
Yes we can have
only try block without catch block.
What is the use of
enumerated data type?
An enumerated data type is another user defined type which provides a
way for attaching names to numbers thereby increasing comprehensibility of the
code. The enum keyword automatically enumerates a list of words by assigning
them values 0,1,2, and so on.
What
is enum in C#?
enum keyword is
used for declaring an enumeration, which consists of named constants and it is
called as enumerator lists. Enums are value types in C# and these can’t be
inherited. Below is the sample code of using Enums
Eg: enum Fruits {
Apple,Orange,Banana,WaterMelon};
What
is an interface class?
It is an abstract class with public abstract methods all of which must
be implemented in the inherited classes.
What
are the different types of Caching?
There are three types of Caching:
Output Caching: stores the responses from an asp.net page.
Fragment Caching: Only caches/stores the portion of page (User Control).
Data Caching: is Programmatic way to Cache objects for performance.
What
are literals and their types?
Literals are value constants assigned to variables in a program. C#
supports several types of literals are
· Integer
literals: Used to write values of types Int, ulnt, long, and ulong.
· Real literals:
Used to write values of types float, double, and dedmal.
· Boolean
literals: True and false are literals of the Boolean type that map to the true
and false state, respectively.
· Single
character literals: Represents a single character and usually consists of a
character in quotes, such as 'a'.
Str
· String
literals
· Backslash
character literals
· The Null
literal: Represents the null–type.
What is the difference
between “dispose” and “finalize” variables in C#?
· Dispose -
This method uses interface – “IDisposable” interface and it will free up both
managed and unmanaged codes like – database connection, files etc.
· Finalize -
This method is called internally unlike Dispose method which is called
explicitly. It is called by garbage collector and can’t be called from the
code.
Why to use “finally”
block in C#?
“Finally” block
will be executed irrespective of exception. So while executing the code in try
block when exception is occurred, control is returned to catch block and at
last “finally” block will be executed. So closing connection to database /
releasing the file handlers can be kept in “finally” block.
What is the difference
between “finalize” and “finally” methods in C#?
· Finalize –
This method is used for garbage collection. So before destroying an object this
method is called as part of clean up activity.
· Finally –
This method is used for executing the code irrespective of exception occurred
or not.
What is the difference
between “throw ex” and “throw” methods in C#?
· “throw ex” will
replace the stack trace of the exception with stack trace info of re throw
point.
· “throw” will
preserve the original stack trace info.
Do we get error while
executing “finally” block in C#?
Yes. We may get
error in finally block.
Mention the assembly
name where System namespace lies in C#?
Assembly Name –
mscorlib.dll
Can we override private
virtual method in C#?
No. We can’t
override private virtual methods as it is not accessible outside the class.
In try block if we add
return statement whether finally block is executed in C#?
Yes. Finally block
will still be executed in presence of return statement in try block.
What you mean by inner
exception in C#?
Inner exception is
a property of exception class which will give you a brief insight of the
exception i.e, parent exception and child exception details.
Explain String Builder
class in C#?
This will represent
the mutable string of characters and this class cannot be inherited. It allows
us to Insert, Remove, Append and Replace the characters. “ToString()” method
can be used for the final string obtained from StringBuilder. For example,
StringBuilder
TestBuilder= new StringBuilder(“Hello”);
TestBuilder.Remove(2,3);
// result- “He”
TestBuilder.Insert(2,”Ip”);
// result- “Help”
TestBuilder.Replace(‘I’,’a’);
// result- “Heap”
How we can sort the
array elements in descending order in C#?
“Sort()” method is
used with “Reverse()” to sort the array in descending order.
Explain circular
reference in C#?
This is a situation
where in, multiple resources are dependent on each other and this causes a lock
condition and this makes the resource to be unused.
Explain object pool in
C#?
Object pool is used
to track the objects which are being used in the code. So object pool reduces
the object creation overhead.
What is Nullable Types
in C#?
Variable types does
not hold null values so to hold the null values we have to use nullable types.
So, nullable types can have values either null or other values as well.
Why to use “Nullable
Coalescing Operator” (??) in C#?
Nullable Coalescing
Operator can be used with reference types and nullable value types. So if the
first operand of the expression is null then the value of second operand is
assigned to the variable. For example,
Double? myFirstno=
null;
double mySecno;
mySecno = myFirstno
?? 10.11;
What is the difference
between “as” and “is” operators in C#?
· “as”
operator is used for casting object to type or class.
· “is” operator
is used for checking the object with type and this will return a Boolean value.
Why to use lock
statement in C#?
Lock will make sure
one thread will not intercept the other thread which is running the part of
code. So lock statement will make the thread wait, block till the object is
being released.
Explain Hashtable in
C#?
It is used to store
the key/value pairs based on hash code of the key. Key will be used to access
the element in the collection.
For example,
Hashtable myHashtbl
= new Hashtable();
myHashtbl.Add("1",
"TestValue1");
myHashtbl.Add("2",
"TestValue2");
How to check whether
hash table contains specific key in C#?
Method –
“ContainsKey” can be used to check the key in hash table. Below is the sample
code for the same –
Eg: myHashtbl.ContainsKey(“1”);
What is the difference
between “continue” and “break” statements in C#?
· “continue”
statement is used to pass the control to next iteration. This statement can be
used with – “while”, “for”, “foreach” loops.
· “break”
statement is used to exit the loop.
Write a sample code to
write the contents to text file in C#?
Below is the sample
code to write the contents to text file –
Using System.IO;
File.WriteAllText(“mytextfilePath”,”MyTestContent”);
Explain Partial Class
in C#?
Partial classes’
concept added in .Net Framework 2.0 and it allows us to split the business
logic in multiple files with the same class name along with “partial” keyword.
Explain Anonymous type
in C#?
This is being added
in C# 3.0 version. This feature enables us to create an object at compile
time. Below is the sample code for the same –
Var myTestCategory
= new { CategoryId = 1, CategoryName = “Category1”};
Name the compiler of
C#?
C# Compiler is –
CSC.
Explain the types of
unit test cases?
Below are the lists
of unit test case types –
· Positive
Test cases
· Negative
Test cases
· Exception
Test cases
Explain Copy
constructor in C#?
If the constructor
contains the same class in the constructor parameter then it is called as copy
constructor.
class MyClass
{
public string
prop1, prop2;
public
MyClass(string a, string b)
{
prop1
= a;
prop2
= b;
}
public
MyClass(MyClass myobj) // Copy Constructor
{
prop1 =
myobj.prop1;
prop2 =
myobj.prop2;
}
}
Explain Static
constructor in C#?
If the constructor
is declared as static then it will be invoked only once for all number of
instances of a class. Static constructor will initialize the static fields of a
class.
class MyClass
{
public string
prop1, prop2;
public
MyClass(string a, string b)
{
prop1 = a;
prop2 = b;
}
Static MyClass()
{
Console.WriteLine(“Static
Constr Test”);
}
public
MyClass(MyClass myobj) // Copy Constructor
{
prop1 =
myobj.prop1;
prop2 =
myobj.prop2;
}
}
Which string method is
used for concatenation of two strings in c#?
“Concat” method of
String class is used to concatenate two strings. For example,
string.Concat(firstStr,
secStr)
Explain Indexers in C#?
Indexers are used
for allowing the classes to be indexed like arrays. Indexers will resemble the property
structure but only difference is indexer’s accessors will take parameters. For
example,
class
MyCollection<T>
{
private T[]
myArr = new T[100];
public T
this[int t]
{
get
{
return
myArr[t];
}
set
{
myArr[t] =
value;
}
}
}
What are the collection
types can be used in C#?
Below are the
collection types in C# -
· ArrayList
· Stack
· Queue
· SortedList
· HashTable
· Bit
Array
Explain Attributes in
C#?
· Attributes
are used to convey the info for runtime about the behavior of elements like –
“methods”, “classes”, “enums” etc.
· Attributes
can be used to add metadata like – comments, classes, compiler instruction etc.
List
out the pre-defined attributes in C#?
Below are the
predefined attributes in C# -
· Conditional
· Obsolete
· Attribute
Usage
What is Thread in C#?
Thread is an
execution path of a program. Thread is used to define the different or unique
flow of control. If our application involves some time-consuming processes then
it’s better to use Multithreading. Which involve in multiple threads.
List out the states of
a thread in C#?
Below are the
states of thread –
· Unstarted
State
· Ready
State
· Not
Runnable State
· Dead
State
Explain the methods and
properties of Thread class in C#?
Below are the
methods and properties of thread class –
· CurrentCulture
· CurrentThread
· CurrentContext
· IsAlive
· IsThreadPoolThread
· IsBackground
· Priority
What are an
ExecuteScalar, ExecuteReader and ExecuteNonQuery?
ExecuteScalar is typically
used when your query returns a single value. If it returns more, then the
result is the first column of the first row. An example might be SELECT @@IDENTITY AS 'Identity'.
ExecuteReader : ExecuteReader
used for getting the query results as a DataReader object. It is readonly
forward only retrieval of records and it uses select command to read through
the table from the first to the last.
SqlDataReader reader;
reader = Command.ExecuteReader();
while (reader.Read()) {
MessageBox.Show(reader.Item(0));
}
reader.Close();
ExecuteNonQuery : ExecuteNonQuery used for
executing queries that does not return any data. It is used to execute the sql
statements like update, insert, delete etc. ExecuteNonQuery executes the
command and returns the number of rows affected.
int retValue = 0;
Command = new SqlCommand(Sql, Connection);
retValue = Command.ExecuteNonQuery();
What
is an assembly and types of assemblies?
Assembly is a unit of deployment like EXE or a DLL.
Types of assembly: - There are two types of assemblies
1) Private assembly: - It is normally used by a single
application and is stored in the application’s directory.
2) Public or Shared assembly: - It is stored in the
global assembly cache, which is a repository of assemblies maintained by the
.net runtime.
What
is variable and dynamic keyword?
Var:-
Introduced in C#3.0
Statically
typed – This means the type of variable declared is decided by the
compiler at compile time.
Dynamic:-
Introduced in C# 4.0
Dynamically
typed - This means the type of variable declared is decided by the
compiler at runtime time.
What
is the difference between “Convert.ToString ()”and “.ToString ()” methods?
Example: - int i=0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i));
We can convert the integer “i” using “i.ToString()” or
“Convert.ToString” so what is the difference. The basic difference between them
is “Convert” function which handles Nulls while “i.ToString()” does not do. It
will throw a Null referencing exception error. So as a good coding practice
using “Convert” is always safe.
What
is the difference between “Enumeration” and “Enum”?
Enumeration: - An enumeration is used in any programming language
to define a constant set of values. The enumeration is defined with the
help of the keyword 'enum'.
Enum: - Is a value type data type. In other words, enumeration
contains its own values and cannot inherit or cannot pass inheritance.
The enum is used to declare a list of named integer constants using
the enum keyword directly inside a namespace, class, or
structure.
The enum is used to give a name to each constant so that the constant
integer can be referred using its name.
What
is the difference between “Dictionary” and “Hash table”?
Dictionary collection is a generic collection equivalent for hash table.
Hash table allows you to add key and value of any type (i.e., Objects).
This leads to two problems one is boxing and unboxing issues and second it’s
not strongly typed.
What
is the use of IEnumerable, ICollection and IDictionary?
IEnumerable: - All collection classes use this interface and
it helps to iterate through all the collection elements.
ICollection: - This interface has the count property and it
is implemented by all collection elements.
IDictionary: - This interface is implemented by hash table
and dictionary.
What
is IEnumerable and IQuerable?
IEnumerable: - It is suitable just for iterate through collection
and you can not modify (Add or Remove) data IEnumerable bring ALL data from
server to client then filter them, assume that you have a lot of records so
IEnumerable puts overhead on your memory.
· IQuerable: - Whenever we encounter to
huge data with so many records so we have to reduce overhead from application.
IQueryable prepares high performance in such situations (huge data) by
filtering data firstly and then sending filtered data to client.
IEnumerable |
IQueryable |
IEnumerable
exists in System.Collections Namespace. |
IQueryable exists
in System. Linq Namespace. |
IEnumerable
doesn’t support custom query. |
IQueryable
supports custom query using CreateQuery and Execute methods. |
IEnumerable
doesn’t support lazy loading. Hence not suitable for paging like scenarios. |
IQueryable
support lazy loading. Hence it is suitable for paging like scenarios. |
IEnumerable
supports deferred execution. |
IQueryable
supports deferred execution. |
IEnumerable is suitable
for LINQ to Object and LINQ to XML queries. |
IQueryable is
suitable for LINQ to SQL queries. |
IEnumerable can
move forward only over a collection, it can’t move backward and between the
items. |
IQueryable can
move forward only over a collection, it can’t move backward and between the
items. |
No comments:
Post a Comment