1. What is the base class of .net?
System.Object
2. What is the difference between “Web.config” and “Machine.Config”?
“Web.config” files apply settings to each web application, while “Machine.config” file apply settings to all ASP.NET applications in the
server.
3. What is compile time and runtime polymorphism?
Method overloading is the example for compile time and method overriding is the example for runtime polymorphism
4. How do you split a string based on a character without using string.split function?
System.Text.RegularExpressions namespace have to be imported to use Regex.Split() method.
5. Can two catch blocks be executed?
No, once the proper catch section is executed the control goes finally to block. So there will not be any scenarios in which multiple
catch blocks will be executed
6. What is the difference between System.String and System.StringBuilder classes?
String is immutable; ie., when a string is modified, a new memory space will be allocated on the heap memory.
StringBuilder can have mutable string where a variety of operations can be performed. (System.Text Namespace)
Append keyword is used in string builder but not in system.string.
Immutable means once we created we cannot modified. Suppose if we want give new value to old value simply it will discarded
the old value and it will create new instance in memory to hold the new value.
7. In what instances you will declare a constructor to be private?
When we create a private constructor, we cannot create object of the class directly from a client. Therefore, you will use private
constructors when you do not want instances of the class to be created by any external client.
8. What does virtual keyword mean?
They signify that method and property can be overridden in the sub class.
Overriding - Virtual keyword
Virtual methods are meant to be re-implemented in derived classes. The C# language provides the override modifier for this
purpose. This keyword specifies that a method replaces its virtual base method
If parent method is marked by keyword “Virtual” but child is not marked by keyword “override”, then program will compile but the
parent method will not be overrided.
If Child method is marked by keyword “override” but parent method is not marked by keyword “virtual” then program will not
compile
9. Can you store multiple data types in System.Array? - No
10. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The first one performs a deep copy of the array, the second one is shallow
11. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
12. What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.
13. Will finally block get executed if the exception had not occurred? Yes.
14. Can multiple catch blocks be executed?
No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows
the finally block.
15. What’s the role of the DataReader class in ADO.NET connections?
It returns a read-only dataset from the data source when the command is executed.
16. Difference between convert.tostring() and .tostring()
convert.tostring() supports null whereas .tostring() will not support null
17. Jump statement in C# - break, continue, goto, return, throw
18. How to assign a value to a readonly variable in C# - using constructor
19. Example of Parameterized datatypes in C# - Generics. Example: List<String>
20. Can an abstract class be declared as sealed?- NO
21. Access specifiers in C# - Public, Private, Protected, internal, protected internal
22. Does C# support static indexers? - No. It supports only instance indexers.
23. Can we put a break statement in a finally block? - NO
24. How do I prevent concurrent access to my data? - lock(this)
25. How to get distinct values from an array in C#? -if (lst.Contains(arr[i]))
26. Difference between Linked List and Array.
The array''s features all follow from its strategy of allocating the memory for all its elements in one block of memory. Linked lists use
an entirely different strategy.
Linked lists allocate memory for each element separately and only when necessary.
An array allocates memory for all its elements lumped together as one block of memory. In contrast, a linked list allocates space for
each element separately in its own block of
memory called a "linked list element" or "node". The list gets is overall structure by using pointers to connect all its nodes together
like the links in a chain.
27. C# Static Class
If a class is declared as static then the variables and methods should compulsorily be declared as static.
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class
using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the
program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to
create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a
static class to hold those methods.
->The main features of a static class are:
•They only contain static members.
•They cannot be instantiated.
•They are sealed.
•They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates
on data when an object is created.
28. What's a static method in c#?
A static method can be accessed from outside the class without creating any object of this class. This static method can be accessed
directly by the name of the static method followed by the . (dot operator) and the class name
29. Can we use a static function with a non-static variable?
No
Static Function in bound to class. So you can not access non static (instance) variable from that function
30. Why main function is static
You need an entry point into your program. Static means that you can call the function without having to instantiate an
object/instance of a class. Its a bit "chicken and egg"... you can't instantiate an object before you're inside the program.
A static method can be called without instantiating an object. Therefore main() needs to be static in order to allow it to be the entry
to your program.
As David says you can just add the keyword static to the function definition to change it. Its worth looking into static (class) methods
vs instance methods, and knowing the difference can be useful at times.
31. How can you write a class to restrict that only one object of this class can be created
(Singleton class)?
32. Rules about Constructors, Destructors, and Finalizers
1: Contrsuctors are called in descending order (top-bottom)
starting from the root class and stepping down through the tree to reach the last leaf object that you need to instantiate
1. In C# lexicology, a destructor and a finalizer refer to the same thing the function called before the object is fully-removed from
the memory
2. Destructors are called in ascending order (bottom-top)
starting from the leaf object that you need to instantiate and moving up through the tree to reach the very first base class of
your object. In reverse of constructors calling order
3. Finalizers are a feature of GC managed objects (i.e. managed classes).
That’s because the finalizer is called only when the GC removes the object from the memory (i.e. frees memory associated
with).
33. How do you declare a static variable and what is its lifetime? Give an example
static int Myint–The life time is during the entire application.
34. Does C# support multiple inheritance? No, use interfaces instead
35. How many types of memories are there in .net?
Ans: Two types of memories are there in .net stack memory and heap memory
36. What is an Abstract Class?
An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be
instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it
but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of
contract that forces all the subclasses to carry on the same hierarchies or standards.
37. What is an Interface?
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.
Both Together
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.
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.
38. What are the differences between Abstract and interface?
1) Abstract cannot be instantiated but we can inherit. Interface it cannot be inherit it can be instantiate
2) Interface contain only declarations no definitions. Abstract contain declarations and definitions.
3) The class which contains only abstract methods is interface class. A class which contains abstract method is called abstract class
4) Public is default access specifier for interface we don’t have a chance to declare other specifiers. In abstract we have chance to
declare with any access specifier
39. When should you use Abstract Class vs Interface while programming?
When we want that sub class must implement all the methods of base class. In such a situation we will implement the interface.
In the other hand when we want only some method of base class in our sub class then use base class as abstract class.
40. If I write System.exit (0); at the end of the try block, will the finally block still execute?
Ans: No in this case the finally block will not execute because when you say system.exit(0),the control immediately goes out of the
program, and thus finally never executes.
41. What is difference between constants, read-only and, static?
Constants: The value can’t be changed
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.
42. What is inheritance?
Inheritance represents the relationship between two classes where one type derives functionality from a second type and then
extends it by adding new methods, properties, events, fields and constants. C# support two types of inheritance:
- Implementation inheritance
- Interface inheritance
43. - During inheritance, if the base class contains only parameterized constructor, then derived class must contain a parameterized
constructor even it doesn’t need one.
44. Polymorphism
Polymorphism means having more than one form. Overloading and overriding are used to implement polymorphism. Polymorphism
is classified into compile time polymorphism or early binding or static binding and Runtime polymorphism or late binding or dynamic
binding.
Polymorphism Examples
•Method Overloading
•Method Overriding
Compile time Polymorphism or Early Binding
The polymorphism in which compiler identifies which polymorphic form it has to execute at compile time it self is called as compile
time polymorphism or early binding.
Advantage of early binding is execution will be fast. Because every thing about the method is known to compiler during compilation
it self and disadvantage is lack of flexibility.
Examples of early binding are overloaded methods, overloaded operators and overridden methods that are called directly by using
derived objects.
Runtime Polymorphism or Late Binding
The polymorphism in which compiler identifies which polymorphic form to execute at runtime but not at compile time is called as
runtime polymorphism or late binding.
Advantage of late binding is flexibility and disadvantage is execution will be slow as compiler has to get the information about the
method to execute at runtime.
Example of late binding is overridden methods that are called using base class object
45. What is implementation and interface inheritance?
When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation
Inheritance.
When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance.
In general Classes can be derived from another class, hence support Implementation inheritance. At the same time Classes can also
be derived from one or more interfaces. Hence they support Interface inheritance.
46. What is inheritance hierarchy?
The class which derives functionality from a base class is called a derived class. A derived class can also act as a base class for
another class. Thus it is possible to create a tree-like structure that illustrates the relationship between all related classes. This
structure is known as the inheritance hierarchy.
47. Describe the accessibility modifier protected internal?
It.s available to derived classes and classes within the same Assembly (and naturally from the base class it.s declared in).
48. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep
the no parameter one. How many constructors should I write?
Ans: - Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself,
even if there.s no implementation in it.
49. 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.
50. Can you override private virtual methods?
No, moreover, you cannot access private methods in inherited classes,have to be protected in the base class to allow any sort of
access.
51. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision
based on UML diagram)?
When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base
abstract methods have been over-ridden.
52. Interface
No data members
No constructors, destructors
Not allow static member
Class members have no implementation
Many classes can implement the same interface
When a class implements an interface, the class must implement the entire interface.
Class can implement more than one interface. The interfaces are separated with a comma.
A class can inherit a base class and also implement one or more interface. In this case, the name of the base class must come
first.
The method that implements an interface must be declared public.
Interface can be inherited
C# support multiple inheritance of interfaces
1. Interface members are always public
2. Only thing the interface can contain is declaration of methods, properties, indexers, and events
A class can implement zero or more interfaces
An interface can extend zero or more interfaces
The implementing method can be virtual or non-virtual
53. Abstract
Comparing Abstract Classes to Interfaces
Similarities
1. Neither can be instantiated
2. Neither can be sealed
Differences
3. Interfaces cannot contain any implementation
4. Interfaces cannot declare non-public members
Interfaces cannot extend non-interfaces
Syntax: Use the abstract keyword
Only abstract classes can declare abstract methods
Abstract methods cannot contain a method body
Abstract methods are virtual
54. Can we call a base class method without creating instance?
Its possible If its a static method.
Its possible by inheriting from that class also.
Its possible from derived classes using base keyword.
55. Difference between type constructor and instance constructor? What is static constructor, when it will be fired? And
what is its use?
(Class constructor method is also known as type constructor or type initializer)
Instance constructor is executed when a new instance of type is created and the class constructor is executed after the type is
loaded and before any one of the type members is accessed. (It will get executed only 1st time, when we call any static
methods/fields in the same class.) Class constructors are used for static field initialization. Only one class constructor per type is
permitted, and it cannot use the vararg (variable argument) calling convention.
A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or
any static members are referenced.
56. What is Private Constructor? and it’s use? Can you create instance of a class which has Private Constructor?
When a class declares only private instance constructors, it is not possible for classes outside the program to derive from the class or
to directly create instances of it. (Except Nested classes)
Make a constructor private if:
- You want it to be available only to the class itself. For example, you might have a special constructor used only in the
implementation of your class' Clone method.
- You do not want instances of your component to be created. For example, you may have a class containing nothing but Shared
utility functions, and no instance data. Creating instances of the class would waste memory.
57. I have 3 overloaded constructors in my class. In order to avoid making instance of the class do I need to make all
constructors to private? (yes)
58. Overloaded constructor will call default constructor internally? (no)
59. Why can.t you specify the accessibility modifier for methods inside the interface?
Ans: - 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, its public by default.
60. How can you overload a method?
Ans: - Different parameter data types, different number of parameters, different order of parameters.
61. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded
constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Ans: - Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded
constructor definition inside the inherited class.
62. What.s the .NET data type that allows the retrieval of data by a unique key? Ans: - Hash Table.
63. What.s a delegate?
Ans:- A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
64. What does assert () do?
Ans: - In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false.
The program proceeds without any interruption if the condition is true.
65. Can you change the value of a variable while debugging a C# application?
Ans: - Yes, if you are debugging via Visual Studio.NET, just go to immediate Window
66. Explain the three services model (three-tier application)?
Ans: - Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
67. When you inherit a protected class-level variable, who is it available to?
Ans :- Classes in the same namespace.
68. How do I read from a text file?
Ans:- First, use a System.IO.FileStream object to open the file:
FileStream fs = new FileStream( @"c:\test.txt", FileMode.Open, FileAccess.Read );
FileStream inherits from Stream, so you can wrap the FileStream object with a StreamReader object. This provides a nice interface
for processing the stream line by line:
StreamReader sr = new StreamReader( fs );
string curLine;
while( (curLine = sr.ReadLine()) != null )
Console.WriteLine( curLine );
Finally close the StreamReader object:
sr.Close();
Note that this will automatically call Close() on the underlying Stream object, so an explicit fs.Close() is not required.
69. How do I write to a text file?
Ans :- Similar to the read example, except use StreamWriter instead of StreamReader.
70. How do I read/write binary files?
Ans :- Similar to text files, except wrap the FileStream object with a BinaryReader/Writer object instead of a
StreamReader/Writer object.
71. How do I delete a file?
Use the static Delete() method on the System.IO.File object:
File.Delete( @.c:\test.txt. );
72. Does C# do array bounds checking?
Ans :- Yes. An IndexOutOfRange exception is used to signal an error.
73. In what instances you will declare a constructor to be private?
When we create a private constructor, we can not create object of the class directly from a client. So you will use private
constructors when you do not want instances of the class to be created by any external client. Example UTILITY functions in project
will have no
74. Can we have different access modifiers on get/set methods of a property ?
No we can not have different modifiers same property. The access modifier on a property applies to both its get and set accessors.
75. If we write a goto or a return statement in try and catch block will the finally block execute ?
The code in then finally always run even if there are statements like goto or a return statements.
76. How can we implement singleton pattern in .NET?
Singleton pattern mainly focuses on having one and only one instance of the object running. Example a windows directory service
which has multiple
Following are the three steps needed to implement singleton pattern in .NET:-
First create your class with static members. Public class ClsStaticClass Private shared objCustomer as clsCustomer End class This
ensures that there is actually only one Customer object throughout the project.
√ Second define a private constructor to your class. Note: - defining a private constructor to class does not allow a client to create
objects directly.
√ Finally provide a static method to get access to your singleton object.
Ado
77. What is the namespace in which .NET has the data functionality classes ?
Following are the namespaces provided by .NET for data management :-
System.data This contains the basic objects used for accessing and storing relational data, such as DataSet,DataTable, and
DataRelation. Each of these is independent of the type of data source and the way we connect to it.
System.Data.OleDB It contains the objects that we use to connect to a data source via an OLE-DB provider, such as
OleDbConnection, OleDbCommand, etc. These objects inherit from the common base classes, and so have the same properties,
methods, and events as the SqlClient equivalents.
System.Data.SqlClient: This contains the objects that we use to connect to a data source via the Tabular Data Stream (TDS)
interface of Microsoft SQL Server (only). This can generally provide better performance as it removes some of the intermediate
layers required by an OLE-DB connection.
78. What.s the role of the Data Reader class in ADO.NET connections?
Ans: - It returns a read-only dataset from the data source when the command isexecuted.
79. What does the parameter Initial Catalog define inside Connection String?
Ans: - The database name to connect to.
80. What.s the data provider name to connect to Access database?
Ans: - Microsoft. Access.
81. Can you give a overview of ADO.NET architecture ?
The most important section in ADO.NET architecture is “Data Provider”. Data Provider provides access to datasource (SQL SERVER,
ACCESS, ORACLE).In short it provides object to achieve functionalities like opening and closing connection, retrieve data and update
data. In the below figure you can see the four main sections of a data provider :-
√ Connection.
Command object (This is the responsible object to use stored procedures)
√ Data Adapter (This object acts as a bridge between datastore and dataset).
√ Datareader (This object reads data from data store in forward only mode).
82. What are the two fundamental objects in ADO.NET ?
Datareader and Dataset are the two fundamental objects in ADO.NET.
83. What is the use of command objects ?
They are used to connect connection object to Datareader or dataset. Following are the methods provided by command object :-
√ ExecuteNonQuery :- Executes the command defined in the CommandText property against the connection defined in the
Connection property for a query that does not return any row (an UPDATE, DELETE or INSERT). Returns an Integer indicating the
number of rows affected by the query.
√ ExecuteReader :- Executes the command defined in the CommandText property against the connection defined in the Connection
property. Returns a "reader" object that is connected to the resulting rowset within the database, allowing the rows to be retrieved.
√ ExecuteScalar :- Executes the command defined in the CommandText property against the connection defined in the Connection
property. Returns only single value (effectively the first column of the first row of the resulting rowset) any other returned columns
and rows are discarded. It is fast and efficient when only a "singleton" value is required
84. What is the use of dataadapter ?
These are objects that connect one or more Command objects to a Dataset object. They provide logic that would get data from the
data store and populates the tables in the DataSet, or pushes the changes in the DataSet back into the data store.
√ An OleDbDataAdapter object is used with an OLE-DB provider
√ A SqlDataAdapter object uses Tabular Data Services with MS SQL Server.
85. What are basic methods of Dataadapter ? There are three most commonly used methods of Dataadapter :- Fill :- Executes the
SelectCommand to fill the DataSet object with data from the data source. It an also be used to update (refresh) an existing table in a
DataSet with changes made to the data in the original datasource if there is a primary key in the table in the DataSet
FillSchema :- Uses the SelectCommand to extract just the schema for a table from the data source, and creates an empty table in
the DataSet object with all the corresponding constraints.
Update:- Calls the respective InsertCommand, UpdateCommand, or DeleteCommand for each inserted, updated,or deleted row in
the DataSet so as to update the original data source with the changes made to the content of the DataSet. This is a little like the
UpdateBatch method provided by the ADO Recordset object, but in the DataSet it can be used to update more than one table.
86. What is Dataset object? The DataSet provides the basis for disconnected storage and manipulation of relational data. We fill it
from a data store,work with it while disconnected from that data store, then reconnect and flush changes back to the data store if
required.
87. What are the various objects in Dataset ? Dataset has a collection of DataTable object within the Tables collection. Each
DataTable object contains a collection of DataRow objects and a collection of DataColumn objects. There are also collections for the
primary keys, constraints, and default values used in this table which is called as constraint collection, and the parent and child
relationships between the tables. Finally, there is a DefaultView object for each table. This is used to create a DataView object based
on the table, so that the data can be searched, filtered or otherwise manipulated while displaying the data.
88. How do we connect to SQL SERVER, which namespace do we use ?
Following are the steps to connect to SQL SERVER :-
√ First import the namespace “System.Data.SqlClient”.
√ Create a connection object as shown in “LoadData” method. With objConnection .ConnectionString = strConnectionString .Open()
End With
√ Create the command object with the SQL. Also assign the created connection object to command object and execute the reader.
√ Finally loop through the reader and fill the list box. If old VB programmers are expecting the movenext command it’s replaced by
Read() which returns true if there is any data to be read. If the .Read() return’s false that means that it’s end of datareader and there
is no more data to be read.
√ Do not forget to close the connection object.
89. Which is the best place to store connectionstring in .NET projects ?264
Config files are the best places to store connectionstrings. If it is a web-based application “Web.config” file will be used and if it is a
windows application “App.config” files will be used.
90. How can we check that some changes have been made to dataset since it was loaded ? How can we cancel all changes
done in dataset ? Twist :- How do we get values which are changed in a dataset ?
For tracking down changes Dataset has two methods which comes as rescue “GetChanges “and “HasChanges”.
91. What’s difference between “Optimistic” and “Pessimistic” locking ? In pessimistic locking when user wants to update data it
locks the record and till then no one can update data. Other user’s can only view the data when there is pessimistic locking. In
optimistic locking multiple users can open the same record for updating, thus increase maximum concurrency. Record is only locked
when updating the record. This is the most preferred way of locking practically. Now a days browser based application is very
common and having pessimistic locking is not a practical solution.
92. How many ways are there to implement locking in ADO.NET ? Following are the ways to implement locking using ADO.NET :-
√ When we call “Update” method of DataAdapter it handles locking internally. If the DataSet values are not matching with current
data in Database it raises concurrency exception error. We can easily trap this error using Try..Catch block and raise appropriate error
message to the user.
√ Define a Datetime stamp field in the table.When actually you are firing the UPDATE SQL statements compare the current
timestamp with one existing in the database. Below is a sample SQL which checks for timestamp before updating and any mismatch
in timestamp it will not update the records. This is the best practice used by industries for locking. Update table1 set field1=@test
where LastTimeStamp=@CurrentTimeStamp
√ Check for original values stored in SQL SERVER and actual changed values. In stored procedure check before updating that the old
data is same as the current. Example in the below shown SQL before updating field1 we check that is the old field1 value same. If
not then some one else has updated and necessary action has to be taken. Update table1 set field1=@test where field1 =
@oldfield1value Locking can be handled at ADO.NET side or at SQL SERVER side i.e. in stored procedures. For more details of how to
implementing locking in SQL SERVER read “What are different locks in SQL SERVER ?” in SQL SERVER chapter
93. How would u connect to database using .NET?
SqlConnection nwindConn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI;" +
"Initial Catalog=northwind");
nwindConn.Open();
94. What is difference between dataset and datareader ?
Following are some major differences between dataset and datareader :-
√ DataReader provides forward-only and read-only access to data, while the DataSet object can hold more than one table (in other
words more than one rowset) from the same data source as well as the relationships between them.
√ Dataset is a disconnected architecture while datareader is connected architecture.
√ Dataset can persist contents while datareader can not persist contents, they are forward only.
95. What is the difference between “DataSet” and “DataReader” ?
Twist :- Why is DataSet slower than DataReader ? Fourth point is the answer to the twist. Note:- This is my best question and I
expect everyone to answer it. It is asked almost 99% in all companies....Basic very Basic cram it. Following are the major differences
between “DataSet” and “DataReader” :-
√ “DataSet” is a disconnected architecture, while “DataReader” has live connection while reading data. If we want to cache data and
pass to a different tier “DataSet” forms the best choice and it has decent XML support.
√ When application needs to access data from more than one table “DataSet” forms the best choice.
√ If we need to move back while reading records, “datareader” does not support this functionality.
√ But one of the biggest drawbacks of DataSet is speed. As “DataSet” carry considerable overhead because of
relations, multiple tables etc speed is slower than “DataReader”. Always try to use “DataReader” wherever possible,
as it’s meant specially for speed performance.
96. Difference between DataReader and DataAdapter / DataSet and DataAdapter?
You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. Using the DataReader
can increase application performance and reduce system overhead because only one row at a time is ever in memory.
After creating an instance of the Command object, you create a DataReader by calling Command.ExecuteReader to retrieve
rows from a data source, as shown in the following example.
SqlDataReader myReader = myCommand.ExecuteReader();
You use the Read method of the DataReader object to obtain a row from the results of the query.
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
myReader.Close();
The DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the
data source. It can be used with multiple and differing data sources, used with XML data, or used to manage data local to the
application. The DataSet represents a complete set of data including related tables, constraints, and relationships among the
tables. The methods and objects in a DataSet are consistent with those in the relational database model. The DataSet can also
persist and reload its contents as XML and its schema as XML Schema definition language (XSD) schema.
The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides
this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes
the data in the data source to match the data in the DataSet. If you are connecting to a Microsoft SQL Server database, you can
increase overall performance by using the SqlDataAdapter along with its associated SqlCommand and SqlConnection. For other OLE
DB-supported databases, use the DataAdapter with its associated OleDbCommand and OleDbConnection objects.
97. Which method do you invoke on the DataAdapter control to load your generated dataset with data?
Fill()
98. Explain different methods and Properties of DataReader which you have used in your project?
Read
GetString
GetInt32
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
myReader.Close();
99. How to check if a datareader is closed or opened? IsClosed()
100. What is the full form of ADO?
The full form of ADO is ActiveX Data Object.
101.Explain ADO.NET in brief.
ADO.NET is a very important feature of .NET Framework, which is used to work with data that is stored in structured data sources,
such as databases and XML files. The following are some of the important features of ADO.NET:
102.Contains a number of classes that provide you with various methods and attributes to manage the communication
between your application and data source.
Enables you to access different data sources, such as Microsoft SQL Server, and XML, as per your requirements.
Provides a rich set of features, such as connection and commands that can be used to develop robust and highly efficient data
services in .NET applications.
Provides various data providers that are specific to databases produced by various vendors. For example, ADO.NET has a separate
provider to access data from Oracle databases; whereas, another provider is used to access data from SQL databases.
103.Explain the DataAdapter.Update() and DataSetAcceptChanges() methods.
The DataAdapter.Update() method calls any of the DML statements, such as the UPDATE, INSERT, or DELETE statements, as the case
may be to update, insert, or delete a row in a DataSet. The DataSet.Acceptchanges() method reflects all the changes made to the
row since the last time the AcceptChanges() method was called.
Mention the namespace that is used to include .NET Data Provider for SQL server in .NET code.
The System.Data.SqlClient namespace.
104.What are the usages of the Command object in ADO.NET?
The Command object in AD0.NET executes a command against the database and retrieves a DataReader or DataSet object.
It also executes the INSERT, UPDATE, or DELETE command against the database.
All the command objects are derived from the DbCommand class.
The command object is represented by two classes: SqlCommand and OleDbCommand.
The Command object provides three methods to execute commands on the database:
The ExecuteNonQuery() method executes the commands and does not return any value.
The ExecuteScalar() method returns a single value from a database query.
The ExecuteReader() method returns a result set by using the DataReader object.
105.What is the difference between the Clone() and Copy() methods of the DataSet class?
The Clone() method copies only the structure of a DataSet. The copied structure includes all the relation, constraint, and DataTable
schemas used by the DataSet. The Clone() method does not copy the data, which is stored in the DataSet.
The Copy() method copies the structure as well as the data stored in the DataSet.
106.What is the use of DataView?
User-defined view of a table is contained in a DataView. A complete table or a small section of table depending on some criteria can
be presented by an object of the DataView class. You can use this class to sort and find data within DataTable.
The DataView class has the following methods:
Find() - Finds a row in a DataView by using sort key value.
FindRows() - Uses the sort key value to match it with the columns of DataRowView objects. It returns an array of all the
corresponding objects of DataRowView whose columns match with the sort key value.
AddNew() - Adds a new row to the DataView object.
Delete() - Deletes the specified row from the DataView object according to the specified index.
107.How can you add or remove rows from the DataTable object of DataSet?
The DataRowCollection class defines the collection of rows for the DataTable object in a DataSet. The DataTable class provides the
NewRow() method to add a new DataRow to DataTable. The NewRow method creates a new row, which implements the same
schema as applied to the DataTable. The following are the methods provided by the DataRowCollection object:
Add() - Adds a new row to DataRowCollection.
Remove()- Removes a DataRow object from DataRowCollection.
RemoveAt() - Removes a row whose location is specified by an index number.
108.Explain in brief DataAdapter class in ADO.NET.
The DataAdapter class retrieves data from the database, stores data in a dataset, and reflects the changes made in the dataset to
the database. The DataAdapter class acts as an intermediary for all the communication between the database and the DataSet
object. The DataAdapter Class is used to fill a DataTable or DataSet Object with data from the database using the Fill() method. The
DataAdapter class applies the changes made in dataset to the database by calling the Update() method.
The DataAdapter class provides four properties that represent the database command:
SelectCommand, InsertCommand, DeleteCommand, and UpdateCommand.
XML
109.Which are the namespaces in .NET used for XML?
“System.xml.dll” is the actual physical file which has all XML implementation. Below are the commonly used namespaces:- √
System.Xml √ System.Xml.Schema √ System.Xml.XPath √ System.Xml.Xsl
110.What are the core functionalities in XML .NET framework? Can you explain in detail those functionalities? The XML
API for the .NET Framework comprises the following set of functionalities
XML readers With XML readers the client application get reference to instance of reader class. Reader class allows you to scroll
forward through the contents like moving from node to node or element to element. You can compare it with the “SqlDataReader”
object in ADO.NET which is forward only. In short XML reader allows you to browse through the XML document.
XML writers Using XML writers you can store the XML contents to any other storage media. For instance you want to store the whole
in memory XML to a physical file or any other media.
XML document classes XML documents provides a in memory representation for the data in an XMLDOM structure as defined by
W3C. It also supports browsing and editing of the document. So it gives you a complete memory tree structure representation of
your XML document.
Explain the XmlReader class.
The XmlReader class is used to read XML data in a fast, forward-only, and non-cached manner. To work with XmlReader class in .NET, you
need to import the following namespace: using System.Xml;
Describe the XmlWriter class.
The XmlWriter class is used to write XML to a stream, a file, or a Textwriter object. This class works in a forward-only, non-cached manner. You
can configure the XmlWriter object up to a large extent. With this object, you can specify a few things, such as whether to indent content or
not, the amount to indent, what quote character to use in attribute values, and whether or not namespaces are supported.
What is XPath?
XPath stands for XML Path. It is a language used to access different parts of an XML document, such as elements and attributes.
What is an XML attribute?
An XML attribute contains additional information regarding that particular element. The XML attributes use the name-value pair. For example,
the element student has an attribute called id and the value of this attribute is set to s01, as shown in the following code snippet:
<Student ID="s01">
...
</Student>
The XML elements cannot be empty. Is it true?
No, it is not true.
Which classes are supported to make an XML DOM?
The following are the different classes in the System.Xml namespace that make up the XML DOM:
The XmlNode class
The XmlDocument Class
The XmlElement Class
The XmlAttribute Class
The XmlText class
The XmlComment class
The XmlNodeList Class
How to read all child nodes of an XML file? And I want to load all entries and then their title, content and thumbnail. But I have problems even
loading the entries. That's my code
XmlDocument xml = new XmlDocument();
xml.LoadXml(data);
XmlNodeList xnList = xml.SelectNodes("feed/entry");
foreach (XmlNode xn in xnList) {
Debug.WriteLine(xn.LocalName.ToString());
Insert Xml node after specific node [closed]
then xml.AppendChild() will add that node at the end only
Insert XML node before specific node using c#
use the insertAfter method:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(yourFile);
XmlNode xElt = xDoc.SelectSingleNode("//name[@ref=\"a2\"]");
XmlElement xNewChild = xDoc.CreateElement("name");
xNewChild.SetAttribute("ref", "b2");
xNewChild.SetAttribute("type", "aaa");
xDoc.DocumentElement.InsertAfter(xNewChild, xElt);
The XmlTextReader Class
The XmlTextReader class is designed for fast, resource nonintensive access to the contents of an XML file Unlike the XmlDocument class, the
XMLTextReader class does not create a node tree of the entire document in memory. Rather, it
and the .NET Framework processes the XML as a forward-only stream
Commonly Needed Properties of the XmlTextReader Class
AttributeCount : Returns the number of attributes of the current node
Depth : Returns the depth (nesting level) of the current node
HasValue : Returns True if the current node can have a value
HasAttributes R: eturns True if the current node has attributes
Commonly Needed Methods of the XmlTextReader Class
GetAttribute(att) :Gets the value of an attribute. Att is a number specifying the position of the attribute, with the first attribute being 0, or a
string specifying the name of the attribute.
IsStartElement() Returns True if the current node is a start element or an empty element.
MoveToAttribute(att) Moves to a specific attribute. Att is a number specifying the position of the attribute, with the first attribute being 0, or a
string specifying the name of the attribute.
MoveToElement() Moves to the element that contains the current attribute.
MoveToFirstAttribute() Moves to the first attribute.
MoveToNextAttribute() Moves to the next attribute.
Read() Reads the next node from the XML file. Returns True on success or False if there are no more nodes to read.
The basic steps required to use the XmlTextReader class are as follows:
1. Create an instance of the class, passing the name of the XML file to process as an argument to the class constructor.
2. Create a loop that executes the Read() method repeatedly until it returns False, which means that the end of the file has been reached.
3. In the loop, determine the type of the current node.
4. Based on the node type, either ignore the node or retrieve node data as needed.
XmlTextWriter Class
The XmlTextWriter class provides the ability to write properly formed XML to a file or other stream. The XML created conforms to the W3C XML
specification version 1.0, and also to the Namespaces in XML specification. Using this
class is straightforward:
1. Create an instance of the class, passing the name of the file to be used for output and the type of encoding to use. Pass a null reference for
the encoding argument to use UTF-8 encoding.
2. Set object properties as needed to control the formatting of the output.
3. Call object methods to write elements and attributes to the file.
4. Close the file.
WriteEndAttribute() Completes an attribute started with WriteStart-Attribute().
WriteEndDocument() Closes any open elements or attributes.
WriteEndElement() Writes the closing tag for an element started with
WriteStartElement(). If the element is empty it will be closed with a short end tag: <element />.
XmlDocument Class
Use XmlTextReader when
1. Memory and processing resources are a consideration, particularly for large documents.
2. You are looking for specific pieces of information in the document. For example, in a library catalog, use XmlTextReader when you need
tolocate all works by a specific author.
3. You do not need to modify the document structure.
4. You want to only partially parse the document before handing it off to another application.
Use XmlDocument when
1.You need random access to all of document’s contents.
2.You need to modify the document structure.
3.You need complex XPath filtering.
4.You need to perform XSLT transformations
Using the XmlDocument Class to Modify an XML Document
//Load the input file.
xmlDoc.Load( m_InFileName );
//Create a new "person" element.
XmlElement elPerson = xmlDoc.CreateElement( "person" );
//Add the "category" attribute.
elPerson.SetAttribute( "category", "family" );
//Create "name," "phone," and "email" elements.
Using XPathNavigator with XmlDocument
The XPathNavigator class is designed specifically to facilitate navigating
through XML that is contained in an XmlDocument object.
111.What is three tier architecture?
The three tier software architecture emerged in the 1990s to overcome the limitations of the two tier architecture. There are three
layers when we talk about three tier architecture:- User Interface (Client) :- This is mostly the windows user interface or the Web
interface but this has only the UI part. Mid layer: - Middle tier provides process management where business logic and rules are
executed and can accommodate hundreds of users (as compared to only 100 users with the two tier architecture) by providing
functions such as queuing, application execution, and database staging. Data Access Layer: - This is also called by the famous
acronym "DAL" component. It has mainly the SQL statement which do the database operation part of the job. The three tier
architecture is used when an effective distributed client/server design is needed that provides (when compared to the two tier)
increased performance, flexibility, maintainability, reusability, and scalability, while hiding the complexity of distributed processing
from the user.
112.What are different ways you can pass data between tiers?
There are many ways you can pass data between tiers :-
√ Dataset the most preferred one as they maintain data in XML format.
√ Datareader
√ Custom classes.
√ XML
113.What is Web Service?
Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web
Services are means for interacting with objects over the Internet. The Web serivce consumers are able to invoke method calls on
remote objects by using SOAP and HTTP over the Web. WebService is language independent and Web Services communicate by
using standard web protocols and data formats, such as
HTTP
XML
SOAP
114.Advantages of Web Service
Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this
message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.
115.Examples for Web Service
Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
News Headline: You can display latest news update by using News Headline Web Service in your website.
116.What is SOAP?
SOAP (simple object access protocol) is a remote function calls that invokes method and execute them on Remote machine and
translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and
sent via HTTP.
117.What is WSDL?
WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts
and which results it will return.
WSDL contains every detail regarding using web service and Method and Properties provided by web service and URLs from which
those methods can be accessed and Data Types used.
118.What is UDDI?
UDDI allows you to find web services by connecting to a directory.
119.How many web.config files are there in 1 project?
Ans: There might be multiple web.config files for a single project depending on the hierarchy of folders inside the root folder of the
project, so for each folder we can use one web.config file
120.What are difference between GET and POST Methods?
Ans:GET Method ():
1) Data is appended to the URL.
2) Data is not secret.
3) It is a single call system
4) Maximum data that can be sent is 256.
5) Data transmission is faster
6) this is the default method for many browsers
POST Method ():
1) Data is not appended to the URL.
2) Data is Secret
3) it is a two call system.
4) There is no Limit on the amount of data. That is characters any amount of data can be sent.
5) Data transmission is comparatively slow.
6) No default and should be explicitly specified.
121.What is WCF?
Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring
and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental
characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined feature of Web Service,
Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.
Advantages of WCF
1) WCF is interoperable with other services when compared to .Net Remoting where the client and service have to be .Net.
2) WCF services provide better reliability and security in compared to ASMX web services.
3) In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small
changes in the configuration will make your requirements.
4) WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology
developer has to write the code.
122.Difference between WCF and Web service
Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service.
Still we are having more advantages over Web service; following table provides detailed difference between them.
Features
Features Web Service WCF
It can be hosted in IIS, windows activation service,
Hosting It can be hosted in IIS
Self-hosting, Windows service
[WebService] attribute has to be added to [ServiceContract] attribute has to be added to the
Programmi
the class class
[WebMethod] attribute represents the [OperationContract] attribute represents the method
Model
method exposed to client exposed to client
One-way, Request- Response are the
One-Way, Request-Response, Duplex are different
Operation different operations supported in web
type of operations supported in WCF
service
System.Xml.serialization name space is used System.Runtime.Serialization namespace is used for
XML
for serialization serialization
XML 1.0, MTOM(Message Transmission
Encoding XML 1.0, MTOM, Binary, Custom
Optimization Mechanism), DIME, Custom
Can be accessed through HTTP, TCP, Named pipes,
Transports Can be accessed through HTTP, TCP, Custom
MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions
123.A WCF Service is composed of three components parts viz
1) Service Class - A WCF service class implements some service as a set of methods.
2) Host Environment - A Host environment can be a Console application or a Windows Service or a Windows Forms application or IIS
as in case of the normal asmx web service in .NET.
3) Endpoints - All communications with the WCF service will happen via the endpoints. The endpoint is composed of 3 parts
(collectively called as ABC's of endpoint) as defines below:
Address: The endpoints specify an Address that defines where the endpoint is hosted. It’s basically url.
Ex:http://localhost/WCFServiceSample/Service.svc
Binding: The endpoints also define a binding that specifies how a client will communicate with the service and the address where
the endpoint is hosted. Various components of the WCF are depicted in the figure below.
"A" stands for Address: Where is the service?
"B" stands for Binding: How can we talk to the service?
"C" stands for Contract: What can the service do for us?
124.Different bindings supported by WCF
Binding Description
BasicHttpBinding Basic Web service communication. No security by default
WSHttpBinding Web services with WS-* support. Supports transactions
WSDualHttpBinding Web services with duplex contract and transaction support
WSFederationHttpBinding Web services with federated security. Supports transactions
MsmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding Communication between WCF applications by using queuing. Supports transactions
Communication between WCF applications on same computer. Supports duplex
NetNamedPipeBinding
contracts and transactions
Communication between computers across peer-to-peer services. Supports duplex
NetPeerTcpBinding
contracts
Communication between WCF applications across computers. Supports duplex
NetTcpBinding
contracts and transactions
BasicHttpBinding Basic Web service communication. No security by default
WSHttpBinding Web services with WS-* support. Supports transactions
125.Contract: The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint;
each endpoint may expose a different set of methods.
Different contracts in WCF
1. Service Contract
Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city
based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.
2. Data Contract
Data contract describes the custom data type which is exposed to the client. This defines the data types, which are passed to and
from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language
document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract
we can make client to be aware of Employee data type that are returning or passing parameter to the method.
3. Message Contract
Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting
your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.
4. Fault Contract
Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can
know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to
client. This helps us to easy identity, what error has occurred.
Overall Endpoints will be mentioned in the web.config file for WCF service like this
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="http://localhost:8090/MyFirstWcfService/SampleService.svc" binding="wsHttpBinding" contract="IService">
<identity>
126.Creating simple application using WCF
First open Visual Studio and click file --> Select New --> Website Under that select WCF Service and give name for WCF Service and
click OK
Once you created application you will get default class files including Service.cs and IService.cs
Here IService.cs is an interface it does contain Service contracts and Data Contracts and Service.cs is a normal class inherited by
IService where you can all the methods and other stuff.
Calling WCF Service using Console Application
After Creation Console application now we need to add WCF reference to our console application for that right click on your windows
application and select Add Service Reference
After that open your app.config file and check your endpoint connection for WCF Service reference that should be like this
127.What is the proxy for WCF Service?
A proxy is a class by which a service client can Interact with the service. By the use of proxy in the client application we are able to
call the different methods exposed by the service.
128.What is endpoint in WCF service?
The endpoint is an Interface which defines how a client will communicate with the service. It consists of three main points:
Address,Binding and Contract.
129.What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.
130.What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address.
This contains the location of the service and transport schemas.
WCF supports following transport schemas
HTTP
TCP
Peer network
IPC (Inter-Process Communication over named pipes)
MSMQ
The sample address for above transport schema may look like
http://localhost:81
131.Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services. They are
1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)
132.What is three major points in WCF?
We Should remember ABC.
Address --- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this
location to communicate with our service.
Binding --- Specifies how the two paries will communicate in term of transport and encoding and protocols
Contract --- Specifies the interface between client and the server.It's a simple interface with some attribute.
133.What is AppSetting Section in “Web.Config” file ?
Web.config file defines configuration for a webproject. Using “AppSetting” section we can define user defined values. Example below
defined is “ConnectionString” section which will be used through out the project for database connection. <configuration>
<appSettings> <add key="ConnectionString" value="server=xyz;pwd=www;database=testing" /> </appSettings>
134.What exactly happens when ASPX page is requested from Browser?
Note: - Here the interviewer is expecting complete flow of how an ASPX page is processed with respect to IIS and ASP.NET engine.
Following are the steps which occur when we request a ASPX page :-
√ The browser sends the request to the webserver. Let us assume that the webserver at the other end is IIS.
√ Once IIS receives the request he looks on which engine can serve this request. When I mean engine means the DLL who can parse
this page or compile and send a response back to browser. Which request to map to is decided by file extension of the page
requested.
Depending on file extension following are some mapping
√ .aspx, for ASP.NET Web pages,
√ .asmx, for ASP.NET Web services,
√ .config, for ASP.NET configuration files,
√ .ashx, for custom ASP.NET HTTP handlers
135.Explain the differences between Server-side and Client-side code?
Server side code is executed at the server side on IIS in ASP.NET framework, while client side code is executed on the browser.
136.How to declare a property in a class?
int m_PersonID = 0;
public int PersonID
{ get { return m_PersonID; } set { m_PersonID = value; } }
137.How to declare a property in an Interface?
DateTime DateOfBirth { get;set;}
int Age { get;set;}
string FirstName { get;set;}
As this is an Interface, so no implementation required only definition of properties are required. Implementation of these properties
will be written into the class inherting this interface.
138.How to declare methods into an Interface
void Calculate();
int Insert(string firstName, string lastName, int age);
Interface doesn't contain implementation so methods implementation will be written into class inherting this interface.
139.Difference Between dispose and finalize method?
Dispose is a method for realse from the memory for an object.
For eg:
<object>.Dispose.
Finalize is used to fire when the object is going to realize the memory.We can set a alert message to says that this object is going to
dispose.
140.What happens if you inherit multiple interfaces and they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a
problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler
cares you’re okay.
141.What are three test cases you should do while unit testing?
Positive test cases : This is done with correct data to check for correct output)
Negative test cases : This is done with broken or missing data to check for proper handling
Exception test cases : This is done with exceptions (giving unexpected data or behavior) and check for the exception caught properly
or not.
142.What is the difference between a.Equals(b) and a == b?
For value types : “==” and Equals() works same way : Compare two objects by VALUE
Example:
int i = 5;
int k= 5;
i == k > True
i.Equals(k) > True
For reference types : both works differently :
“==” compares reference – returns true if and only if both references point to the SAME object while
"Equals" method compares object by VALUE and it will return true if the references refers object which are equivalent
143.Can we declare a class as Protected?
No, a class can not be declared as Protected.
144.A class can be declared with only following access modifiers.
Abstract
Internal
Public
Sealed
Static
145.Some facts about Virtual methods.
Virtual keyword is used to declare a method inside the base class that can be overridden.
Following conditions are applied to a virtual method
1. Virtual method can not be declared as Private
2. Virtual method can not be declared as Static
3. Virtual method may or may not be overridden.
4. In order to override the virtual method of the base class, Override keyword is used provided the method signature of the derived
class is same as base class, even the access modifier should be same.
5. A Virtual method must contain the method body otherwise compiler shall throw error.
6. Virtual keyword is only used in base and derived class scenario where you want your method over-ridable in the derived class.
146.Explain About ref and out parameters?
ref parameter:
Ref is keyword.
it must be used along with actual and formal arguments.
ref variables must be initialized before passing to a function
out parameter:
It is very similar to call by Reference.
Out is a Keyword.
147.Which must be used along with actual and formal arguments.
Out variables are not require to initialize, the initialized value will not be passed, only reference will be passed.
148.Define different Access modifiers in C#
The access modifier is the key of Object Oriented Programming, to promote encapsulation, a type in C# should limit its accessibility
and this accessibility limit are specified using Access modifiers.
They are - Public, Internal, Protected, Private, Protected Internal
Public:
When used that type (method or variable) can be used by any code throughout the project without any limitation. This is the widest
access given to any type and we should use it very judiciously. By default, enumerations and interface has this accessibility.
Internal
When used that type can be used only within the assembly or a friend assembly (provided accessibility is specified using
InternalVisibleTo attribute). Here assembly means a .dll.
For example if you have a .dll for a Data Access Layer project and you have declared a method as internal, you will not be able to
use that method in the business access layer)
Similarly, if you have a website (not web application) and you have declared internal method in a class file under App_Code then you
will not be able to use that method to another class as all classes in website is compiled as a separate .dll when first time it is
called).
Internal is more limited than Public.
Protected
When used that type will be visible only within that type or sub type. For example, if you have a aspx page and you want to declare
a variable in the code behind and use it in aspx paeg, you will need to declare that variable as at least protected (private will not
work) as code behind file is inherited (subclass) by the aspx page.
Protected is more secure than Internal.
Private
When used that type will be visible only within containing type. Default access modifier for methods, variables. For example, if you
have declared a variable inside a method, that will be a private variable and may not be accessible outside that method.
Private is the most secure modifiers than any other access modifiers as it is not accessible outside.
Protected Internal
This is not a different type of access modifiers but union of protected and internal. When used this type will be accessible within
class or subclass and within the assembly.
149.When does GarbageCollector runs ?
Garbage Collector runs :
1. When the system has low physical memory
2. Acceptable memory heap is increased.
3. GC.Collect method is called.
What is Regular Expressions in C#.NET?
The Regular Expressions are the languages which identifies character patterns. Basically this is used for the following tasks such as:
• To validate the text input such as passwords, numbers etc.
• Parsing the textual data into more structured forms. For example, extracting data from an HTML page to store in database.
• Replacing the pattern of text into a document.
All Regular Expression types are defined in System.Text.RegularExpressions .
150.What is the use of virtual, sealed, override, and abstract?
• The use of virtual keyword is to enable or to allow a class to be overridden in the derived class.
• The use of sealed keyword is to prevent the class from overridden i.e. you can’t inherit sealed classes.
• The use of override keyword is to override the virtual method in the derived class.
• The use of abstract keyword is to modify the class, method, and property declaration. You cannot directly make calls to an abstract
method and you cannot instantiate an abstract class.
151.Can we overload static constructors?
No, static constructors are parameterless constructors and so they cannot be overloaded. Static constructors are called before any
other class members are called and called once only.Their main purpose is to initialize only the static members of a class.
152.What are value types and reference types?
Value Type:
A Value Type stores its contents in memory allocated on the stack. When you created a Value Type, a single space in memory is
allocated to store the value and that variable directly holds a value. If you assign it to another variable, the value is copied directly
and both variables work independently. Predefined datatypes, structures, enums are also value types, and work in the same way.
Value types can be created at compile time and Stored in stack memory, because of this, Garbage collector can't access the stack.
int x = 10;
Reference Type:
Reference Types are used by a reference which holds a reference (address) to the object but not the object itself. Because reference
types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the
data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value.
Reference Type variables are stored in a different area of memory called the heap. This means that when a reference type variable is
no longer used, it can be marked for garbage collection. Examples of reference types are Classes, Objects, Arrays, Indexers,
Interfaces etc.
e.g. int[] iArray = new int[20];
In the above code the space required for the 20 integers that make up the array is allocated on the heap.
153. What is the difference between method overriding and method overloading?
Overloading: is the mechanism to have more than one method with same name but with different signature (parameters). A method
can be overloaded on the basis of following properties
Have different number of parameter
Having same number of parameters but of different type
Having same number and type of parameters but in different orders
A method cannot be overloaded on the basis of
Different return type
Different access modifier
Normal and optional parameters
n the same way we can overload constructor of a class by defining more than one constructor with different parameters which is
known as constructor overloading.
Overriding: Overriding can be done in derived class, an override method provides a new implementation of a method inherited
from parent class.
To override a method in base (parent) class it must be
virtual
abstract
override
We cannot override a base method which is in base class as
non-virtual
static
We cannot use the following modifiers to modify an override method in derived class
new
static
virtual
abstract
Conclusion:
Overloading can be done in same class
Overriding can be done in parent and derived class
Overloading in used when we need same method in same class with different parameters
Overriding is used when we need to redefine a method that has already been defined in parent class (using the exact same
signature
Overloading is resolved at compile time
Overriding is resolved at run time
154.Can you mark static constructor with access modifiers?
No, we cannot use access modifiers on static constructor.
155.Can you have parameters for static constructors?
No, static constructors cannot have parameters.
156.What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the
lifetime of the application domain in which your program is running.
Give 2 scenarios where static constructors can be used?
1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the
LoadLibrary method.