Sunday, 1 May 2016

.Net Questions

1. Diff b/w const and read-only
2. What finally block will do?
3. Diff b/w ref and out keywords
4. What is boxing and unboxing?
5. What is reflection?
6. Nullable Types in C#?

Thursday, 28 April 2016

Exception Hnadling

1.What is an Exception?

 An exception is an error that occurs during program execution. Generally, an exception describes an unexpected event. For example, an exception will occur if a program requests more memory than the operating system can provide. This exception is known as an Out of Memory Exception.

2.Exception Handling in C#?
Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.
4.Why is it a bad idea to throw your own exceptions?

 Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.


 5.What is the purpose of the finally block?


 The code in finally block is guaranteed to run, irrespective of whether an error occurs or not. Critical portions of code, for example release of file handles or database connections, should be placed in the finally block.


 6.How do you handle errors in C#?


 C# and VB.NET use structured error handling (unlike VB6 and earlier versions where error handling was implemented using Goto statement). Error handling in both VB.NET and C# is implemented using Try..Catch..Finally construct (C# uses lower case construct – try…catch…finally).

7.Describe how exceptions are handled by the CLR?

  Usually the exceptions that occur in the try are caught in the catch block. The finally is used to do all the cleaning up work. But exceptions can occur even in the finally block. By using CLR, the exception are caught even in the finally block. Also when an exception is thrown, the CLR looks for an appropriate catch filter that can handle the exception and then it executes the finally block before terminating the execution on the catch filter.

8.Does C# have a 'throws' clause?


 No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw.


9.When should I throw an exception?


 This is the subject of some debate, and is partly a matter of taste. However, it is accepted by many that exceptions should be thrown only when an 'unexpected' error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap.


10.what is the difference between finally and  finalize() ?

finally:- It is a block associated with try catch to maintain cleanup code. Finally block will be executed always irrespective of whether exception is raised or not raised or whether the exception is handle or not handle.


finalize():- It is a method, Garbage collector always calls this method just before destroying any object to perform cleanup activities.


11.Difference between "throw" and "throw ex" in .NET?

If you use "throw" statement, it preserve original error stack information.
If you use"throw ex" statement, stack trace of the exception will be replaced with a stack trace starting at the re-throw point.

12.What is the difference between system exceptions and application ?

 System.SystemException -> This class is for exceptions that r usually thrown by the .net runtime, or which r considered to be of a generic nature and must be thrown by almost any application. For example, StackOverflowException will be thrown by the .net runtime if it detects the stack is full.

 System.ApplicationException-> This class is important, becoz it is the intended base for any class of exception defined by third parties. Hence, if u define any exceptions covering error conditions unique to ur application, u should derive these directly or indirectly from System.ApplicationException.

13.A try block having 4 catch block will fire all catch block or not?

 No, A try having more than one catch block will fire the first relevant catch block after that cursor will be moved to the finally block (if exists) leaving all remaining catch blocks. 

So in all cases only one catch block will fire.



14.Can we have try block without catch?


 Yes,We can write Try { } Finally { } block. In this case exception will be thrown in try block if it is but code inside finally block will execute.

15.can we write return statement in try catch or finally block?

 Yes,We can write the return statement in try catch & finally. The only thing is that even if we write return statement in try bloack or catch block the finally block will always get executed.The only case in which finally block does not execute is when we write System.Environment.Exit(0) in either try or catch.

16.Explain Try/catch block of exception handling?

 You can enclose code in Try/Catch/Finally block. You can catch all exceptions in the catch block. The third part of this block is finally. It is executed irrespective of the fact that an exception has been raised.

17.When can you use tracing with exception handling?

 You can use tracing with exception handling to log unanticipated exception to the trace log. The log file can be used to diagnose unanticipated problems and thus can be corrected.

18.What are the two diff types of error?
 Run time error and Compile time error.

19. What is the purpose of throw?

In C#, it is possible to explicitly throw an exception, from the program. The throw keyword is used for doing that. The general form of throwing an exception is as follows. 


System.Exception exception_obj = new ArgumentException("This is my Exception message");
throw exception_obj;



or 



throw new ArgumentException("This is my Exception message");





20.What are different types of exception properties ?


 Helplink-- provide link to help files which give more info on the exception raised.
 Message--gives the text that describes the exception.
    Suppose

catch(Exception e)

    {
    throw new Exception("Failure")
     }
  then e.Message will give output as "Failure".
Source--provides the name of assembly from where exception is raised.
Target Site--name of method that throws an error
Stack Trace--provides stack flow of the exception.

Inner Exception--When exception is thrown from one catch to another the message     from first catch is passed as inner exception to second catch.

21.Is it mandatory for a piece of code to have catch or finally when try block is there ?


 Yes. If a try block is there then either catch or finally has to be there or else a compiler error is generated.



22.Does finally get executed if the code throws an error ?



 Finally is always executed.


23. How to throw a custom exception?

  The usual try - catch - finally - entry format has to be followed. However, in this case, instead of using the preset exceptions from the System. Exception, you define your own Exception class and inherit Exception or Application Exception class.
You need to define three constructors in your Own Exception Class: One without parameters, other with String parameter for error message and the last one has to have one parameter as a String and other as an Inner exception object.

24: Can we get Exception in finally block?

yes, we may get.

25: In which assembly System namespace is there?

mscorlib.dll assembly contain system namespace

26. What is the purpose of Exception Handling?


An exception can occur anytime during the execution of an application. Your application must be prepared to face such situations. An application will crash if an exception occurs and it is not handled.
"An exception handler is a piece of code which will be called when an exception occurs.


27. Is finally block will be execute always?


Yes finally block will be executed always irrespective of whether exception raised or not raised whether exceptions are handled or not handle. There is one situation where the finally block won’t be executed if the CLR is going to be shutdown.


28. If return statement present inside try is finally block will be executed?


Ans. Yes, if return statement present inside try, then also finally block will be executed. finally block will dominate return statement also.

29.  Is it possible to write any statement between try-catch and finally?

Ans. No, it is not possible to write any statement between try catch and finally. If we will try to write any statement between them then we will get compile time error.


30.    After throw is it allow to take any statement directly?


Ans.  After throw statement we are not allow to place any statement directly violation leads to compile time error saying Unreachable Statements.


31.If no exception handling is provided in the program, what will happen ? 

 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.

32.What is Inner Exception?

The InnerException is a property of an exception. When there are series of exceptions, the most current exception can obtain the prior exception in the InnerException property. 


Let us say we have an exception inside a try block throwing an ArgumentException and the catch clause catches it and writes it to a file. However, if the file path is not found, FileNotFoundException is thrown. Let's say that the outside try block catches this exception, but how about the actual ArgumentException that was thrown? Is it lost? No, the InnerException property contains the actual exception. This is the reason for the existence of an InnerException property for any exception.

Wednesday, 20 January 2016

Components of .Net Framework

Components of .Net Framework

There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of .Net Framework.
Components of .Net Framework
Components.jpg
Net Framework is a platform that provides tools and technologies to develop Windows, Web and Enterprise applications. It mainly contains two components,

1. Common Language Runtime (CLR)
2. .Net Framework Class Library.
1. Common Language Runtime (CLR)

.Net Framework
provides runtime environment called Common Language Runtime (CLR).It provides an environment to run all the .Net Programs. The code which runs under the CLR is called as Managed Code. Programmers need not to worry on managing the memory if the programs are running under the CLR as it provides memory management and thread management.

Programmatically, when our program needs memory, CLR allocates the memory for scope and de-allocates the memory if the scope is completed.

Language Compilers (e.g. C#, VB.Net, J#) will convert the Code/Program to Microsoft Intermediate Language (MSIL) intern this will be converted to Native Codeby CLR. See the below Fig.
MSILCode.jpg
There are currently over 15 language compilers being built by Microsoft and other companies also producing the code that will execute under CLR.

2. .Net Framework Class Library (FCL)

This is also called as Base Class Library and it is common for all types of applications i.e. the way you access the Library Classes and Methods in VB.NET will be the same in C#, and it is common for all other languages in .NET.

The following are different types of applications that can make use of .net class library.
1. Windows Application.
2. Console Application
3. Web Application.
4. XML Web Services.
5. Windows Services.
In short, developers just need to import the BCL in their language code and use its predefined methods and properties to implement common and complex functions like reading and writing to file, graphic rendering, database interaction, and XML document manipulation.

Below are the few more concepts that we need to know and understand as part of this .Net framework.

3.
Common Type System (CTS)

It describes set of data types that can be used in different .Net languages in common. (i.e), CTS ensures that objects written in different .Net languages can interact with each other.

For Communicating between programs written in any .NET complaint language, the types have to be compatible on the basic level.

The common type system supports two general categories of types:

Value types:


Value types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be built-in (implemented by the runtime), user-defined, or enumerations.

Reference types:


Reference types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates.

4. Common Language Specification (CLS)

It is a sub set of CTS and it specifies a set of rules that needs to be adhered or satisfied by all language compilers targeting CLR. It helps in cross language inheritance and cross language debugging.

Common language specification Rules:


It describes the minimal and complete set of features to produce code that can be hosted by CLR. It ensures that products of compilers will work properly in .NET environment.

Sample Rules:
1. Representation of text strings
2. Internal representation of enumerations
3. Definition of static members and this is a subset of the CTS which all .NET languages are expected to support.

4. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.
Below mentioned the .Net Architecture stack for easy understanding.

dotnet framework stack.png