Get Paid By Click

Mginger Mobile Money

Jun 30, 2010

Interview Questions And Answers in C# and .NET

What is a Class?class represents an entity in a program

What is .NET ?
It is a platform neutral framework.
Is a layer between the operating system and the programming language.
It supports many programming languages, including VB.NET, C# etc.
.NET provides a common set of class libraries, which can be accessed from any .NET based programming language. There will not be separate set of classes and libraries for each language. If you know any one .NET language, you can write code in any .NET language!!
In future versions of Windows, .NET will be freely distributed as part of operating system and users will never have to install .NET separately.
What is Not ?
.NET is not an operating system.
.NET is not a programming language.
".NET is a framework"

What is Visual Studio.NET ?
VS.NET is just an editor, provided by Microsoft to help developers write .NET programs easily 

.NET supported languages
Currently .NET supports the following languages:
C#
VB.NET
C++
J#

C# or VB.NET ? Which one to choose ? 
 Whether you write code in VB.NET or C#, when you compile, your code will get converted to MSIL (Microsoft Intermediate language). It is this MSIL which you deliver to your customer in the form of a DLL or EXE. The MSIL is executed by the same .NET framework, whether you wrote it originally in C# or VB.NET. 

Is .Net platform independent ? 
 The code you write is platform independent, because whatever you write is getting compiled into MSIL. There is no native code, which depends on your operating system or CPU. But when you execute the MSIL, the .NET framework in the target system will convert the MSIL into native platform code.
Property 
The following code snippet shows how to create "Property" in a class.
public class Car
{
  // private fields.
  private string color;

  // constructor
   public Car()
  {
  }

 public string Color
 {
    get
   {
     return color; // return the value from privte field.
   }
  set
  {
    color = value; // save value into private field.
  }
}
}


Car car = new Car();
car.Color = "RED";
 

The main advantage over using a Property instead of a public field is, with the property, you will get a chance to write few lines of code (if you want) in the get and set accessors. So, you can perform some validation or any other logic before returning any values or assigning to the private field. 
Namespaces 
A Namespace is a group of related classes. It is a good practice to group related classes into a namespace when you create a class library.The main advantage of using namespace, to avoid conflicts when you have multiple classes with the same name
System
System.Xml
System.Data
System.Data.OleDb
System.Data.SqlClient
usage of following .NET classes and methods:
System.IO.Path.GetExtension() - Method to check the extension of a file.
System.IO.File.Exists() - Check if a file alread exists.
System.Windows.Forms.OpenFileDialog - "File Open Dialog" to choose a file from the disk.
DialogResult.OK - Result from a File Open Dialog.
MessageBox.Show() - Displaying a message to the user.
string.Trim() - Remove white space characters from beginning and end of string.
throw new Exception() - Create and throw a new exception.
System.IO.StreamWriter - Stream writer to write into files.
System.IO.StreamReader - Read from file.
Application.Exit() - Closing an application.
Configuration File
 .NET gives an easy way to store configuration information in a ApplicationConfiguration File. In the simple implementation, you can store information as Key-Value pairs.

.NET gives you a simple and easy solution for this problem - the ApplicationConfiguration File. Each application can have a configuration file, which is actually an XML file. You can use any text editor (including notepad) to open the configuration file and change the values. The application will load the values from this configuration file and you do not have to change your source code everytime you change your DataSource or any other information stored in configuration file.
Windows applications in VS.NET uses the name 'app.config' by default for the configuration file. This will not be automatically created when you create a Windows application

 web.config for web applications
The web applications use the same concept, but they use a config file with the name 'web.config'. There are couple of things to note in this case.
web.config is created automatically by VS.NET when you create any web project.
When you compile the web application, web.config is NOT renamed or copied to the BIN folder.
web.config has several default entries in it to support web/IIS configuration & security.
You can add the section in the web.config and add your key/value pairs in that section.
You can have separate web.config files for each directory in your web application, in addition to the one in the root. For each web page, by default system will look for a web.config in the same folder as the page and if not 

found, then looks in the parent folder.
ADO.NET 


ADO.NET is the data access model that comes with the .NET Framework. ADO.NET provides the classes required to communicate with any database source (including Oracle, Sybase, Microsoft Access, Xml, and even text files).
A DATA PROVIDER is a set of classes that can be used to access, retrieve and manipulate data from the databases.
Both OleDb and SqlClient has its own set of classes, but they have the same concepts.We would like to classify the classes into two broad categories
1 Classes for communicate with database
2 Classes for holding/manipulating data
The job of first category of classes is to communicate with database and send or retrieve data from the database. The second category of the classes will be used as a carrier of data.
Classes for communicating with database
The Connection, Command, DataReader, and DataAdapter
objects are the core elements of the ADO.NET provider model

Objects:
Connection-Establish a connection to the specific Datasource
Command-Execute a command against datasource
DataReader-Reads a Readonly datastream of data from a data source 
DataAdapter-Populate Dataset.


The following are the main classes used to hold data in Ado.NET:

DataSet
DataTable
DataRow

A DataSet is an in-memory representation of the database.
DataSet contains DataTables (and more...)
DataTable represents a database table
DataTable contains DataRows (and more...)
A DataRow represents a record in a database table.
DataRow is a collection of all fields in a record.
A DataSet is an in memory representation of data loaded from any data source. Even though the most common data sourceis database, we can use DataSet to load data from other data sources including XML files etc.

DataSet represents an in memory representation of the database. We can load an entire database into a DataSet and manipulate the data in memory. If you aremore familiar with DataSet, you can Add, Edit and Update data in the dataset and then just call a single method 'AcceptChanges()' whichwill save all the changes back to the database.


Method : GetXml()
The GetXml() method returns the XML representation of the data from the DataSet.


Method : WriteXml(...)
The WriteXml() method allows to save XML representation of the data from the DataSet to an XML file


Method : ReadXml(...)
The ReadXml() method allows to load the DataSet from an XML representation of the data. 


What is an 'Exception' ?
'Exception' is an error situation that a program may encounter during runtime. For example, your program may be trying to write into a file, but your hard disk may be ful


Error is an expected situation in an application. For example, you want to create a file in the folder "C:\Projects\Test\". If you attempt to create a file when this folder doesn't exists, it will make the operating system throw an exception. But you should not leave it to the operating system to throw the exception. This has to be handled through code. You must first check for the existence of the folder before you attempt to write the file. If the folder doesn't exists, you must first create the folder. This is how a stable application should be written.



Exception is a runtime error that the program may encounter during the execution of the program. For example, hard disk may be full when you attempt to write into a file, network connection may be lost while your application is communicating with another computer etc. There is no clear definition, but typically, Exceptions are unpredictable errors during runtime.
"An exception handler is a piece of code which will be called when an exception occurs."
 The keywords try, catch are used to handle exceptions in .NET. You have to put the code (that can cause an exception) in a try block. If an exception occurs at any line of code inside a try block, the control of execution will be transfered to the code inside the catch block. 
Syntax :

try
{
// Code which can cause an exception.
}
catch(Exception ex)
{
// Code to handle exception
}
 If any statement within the try block raises an exception, the control of execution will be transfered to the first line within the catch block. You can write the error handling code in the catch block, like recording the error message into a log file, sending an email to the administrator about the problem occurred, showing an appropriate error message to the user etc.

See the following code :



try
{
Statement 1
Statement 2
Statement 3
}
catch(Exception ex)
{
Statement 4
Statement 5
}
 
Statement 6
In normal flow of program, the statements 1, 2, 3, 6 will be executed. Statements 4 and 5 will be executed only if an exception occurs.

Assume there is an exception at statement 2. In this scenario, statements 1, 2, 4, 5 and 6 will be executed. Statement 3 will not be executed at all, because an exception occurred at statement 2 and program flow was transferred to the catch block.

'finally' block

You can optionally use a 'finally' block along with the try-catch. The 'finally' block is guaranteed to be executed even if there is an exception.

Sample Code :



try
{
Statement 1
Statement 2
Statement 3
}
catch(Exception ex)
{
Statement 4
Statement 5
}
finally
{
Statement 6
Statement 7
}
 
Statement 8


In normal flow of program, the statements 1, 2, 3, 6, 7 and 8 will be executed. Statements 4 and 5 will be executed only if an exception occurs.

Assume there is an exception at statement 2. In this scenario, statements 1, 2, 4, 5, 6, 7 and 8 will be executed.

Note that the statements 6 and 7 are executed in both the cases. The bottom line is, the code within the 'finally' block is executed whether there is an exception or not.

You can use the finally block to do any code cleanup. For example, you are doing some database operations inside a try block.



try
{
Statement 1 - Open database
Statement 2 - Execute Query
Statement 3 - Close Database
}
catch(Exception ex)
{
Statement 4 - Show messagebox to user
}


In the above code sample, what will happen if an exception occurs when the statement 2 is executed ? The catch block will be executed and a message box will be shown to the user. But the Statement 3 is never executed in that case, which means the database will not be closed.

Here is where the finally block will be helpful.


try
{
Statement 1 - Open database
Statement 2 - Execute Query
}
catch(Exception ex)
{
Statement 3 - Show messagebox to user
}
finally
{
Statement 4 - Close Database
}


See the improved code. We have moved the code to close the database to the 'finally' block. The statement to close the database will be executed whether there is an exception or not.
In normal flow of program, the statements 1, 2, 3, 6 will be executed. Statements 4 and 5 will be executed only if an exception occurs.

Assume there is an exception at statement 2. In this scenario, statements 1, 2, 4, 5 and 6 will be executed. Statement 3 will not be executed at all, because an exception occurred at statement 2 and program flow was transferred to the catch block.

'finally' block

You can optionally use a 'finally' block along with the try-catch. The 'finally' block is guaranteed to be executed even if there is an exception.

Sample Code :



try
{
Statement 1
Statement 2
Statement 3
}
catch(Exception ex)
{
Statement 4
Statement 5
}
finally
{
Statement 6
Statement 7
}
 
Statement 8


In normal flow of program, the statements 1, 2, 3, 6, 7 and 8 will be executed. Statements 4 and 5 will be executed only if an exception occurs.

Assume there is an exception at statement 2. In this scenario, statements 1, 2, 4, 5, 6, 7 and 8 will be executed.

Note that the statements 6 and 7 are executed in both the cases. The bottom line is, the code within the 'finally' block is executed whether there is an exception or not.

You can use the finally block to do any code cleanup. For example, you are doing some database operations inside a try block.



try
{
Statement 1 - Open database
Statement 2 - Execute Query
Statement 3 - Close Database
}
catch(Exception ex)
{
Statement 4 - Show messagebox to user
}


In the above code sample, what will happen if an exception occurs when the statement 2 is executed ? The catch block will be executed and a message box will be shown to the user. But the Statement 3 is never executed in that case, which means the database will not be closed.

Here is where the finally block will be helpful.


try
{
Statement 1 - Open database
Statement 2 - Execute Query
}
catch(Exception ex)
{
Statement 3 - Show messagebox to user
}
finally
{
Statement 4 - Close Database
}


See the improved code. We have moved the code to close the database to the 'finally' block. The statement to close the database will be executed whether there is an exception or not.
Why should we catch exceptions ?
Why should you use a helmet when you ride a bike ? To protect your head from crashing when there is an accident, right ? Just like that, exception handling will protect your application from crashing when there is an exceptions.

If an exception is not 'handled' in code, the application will crash and user will see an ugly message. Instead, you can catch the exception, log the errors and show a friendly message to the user.


try
{
// Code which can cause a web exception or arithmetic exception.
}
catch(System.Web.HttpException ex)
{
MessageBox.Show ( "A web exception occurred." );
}
catch(System.ArithmeticException ex)
{
MessageBox.Show ( "An arithmetic exception occurred." );
}
Program Flow

When an exception occurs within a try block, the program control will jump to the first catch block and compare if the exception type is same the as the type specified in the catch block. If the type matches, it will execute the catch block. If the types do not match, it will jump to the next catch block and compare. Like this, it will compare against all catch blocks until a match is found. If there is no catch block found which matches the exception type, it will become an unhandled exception and will lead to program termination
Catch derived exceptions first and base exception last
Some commonly used .NET Exception classes
System.ArithmeticException - This is the base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException and System.OverflowException.

System.ArrayTypeMismatchException
- ArrayTypeMismatchException is thrown when a an incompatible object is attpemted to store into an Array.

System.DivideByZeroException
- This exception is thrown when an attempt to divide a number by zero.

System.IndexOutOfRangeException - IndexOutOfRangeException is thrown when attempted to access an array using an index that is less than zero or outside the bounds of the array.

System.InvalidCastException - Thrown when an explicit type conversion from a base type or interface to a derived type fails at run time.

System.NullReferenceException - This exception is thrown when an object is accessed but it is null.

System.OutOfMemoryException - OutOfMemoryException is thrown if the 'new' operation (creating new object) fails due to in sufficient memory.

System.OverflowException - OverflowException is thrown when an arithmetic operation overflows.

System.StackOverflowException - StackOverflowException is thrown when the execution stack is exhausted by having too many pending method calls, most probably due to infinite loop.

ArgumentException - The exception that is thrown when one of the arguments provided to a method is not valid.

XML & HTML 
XML stands for eXtended Markup Language. XML has some similarities to HTML, which is also another Markup Language (HyperText Markup Language).

An important difference between XML and HTML is, XML is used to define data, while HTML is basically used to display/format text. Main use of HTML is to make web pages. But XML is used in a wide variety of applications now and is becoming a standard for data exchange between different paltforms.
Unlike HTML, XML has no pre-defined set of tags. You can define your own tags to structure and organize your data.

 Any XML document can have it's own set of tags. Only thing is, a valid XML document should follow some rules (like each tag should have a matching closing tag. There more such rules...)

In real world, if you have to store data, you have several choices. One of the most common mechanism is databases. Databases are the best choice if you have lot of data to be stored/manipulated. But if you have to send data to another application or platform, databases will not be much helpful.
There are several XML viewers and editors available, which will help you read XML in the form of a tree view. Internet Explorer is a good XML viewer.
The XML data altogether is called an 'XML Document'. .

What is HTML

HTML(Hypertext Markup Language) - is the language used for creating hypertext documents (web pages) and controlling how Web pages appear.

Even though it is a language, it is different from other programming languages like C++ or Java. In languages like C++ and Java, you can write complex applications and the language has its own syntax and rules. But you can use HTML to develop only web pages.

Some facts about HTML

HTML is plain text, composed of tags.
HTML tags are always enclosed in angle-brackets ( < >)
HTML is not case sensitive, that means, it doesn't matter whether you type them in lower case or upper case.
Tags typically are used in begin-end pairs. Most of the HTML tags have an open tag and a close tag

Easy Way To Pay

Sign up for PayPal and start accepting credit card payments instantly.

Earn While Searching