Introduction
What is garbage collection?
Garbage collection is a CLR feature, which automatically manages memory. Programmers forget to release the objects while coding ... Laziness (Remember in VB6 where one of the good practices is to set object to nothing). CLR automatically releases objects when they are no longer in use and refernced. CLR runs on non-deterministic to see the unused objects and cleans them. One side effect of this non-deterministic feature is that we cannot assume an object is destroyed when it goes out of the scope of a function. We should avoid using destructors because before GC destroys the object it first executes destructor in that case it will have to wait for code to release the unmanaged resource. This results in additional delays in GC. So it is recommended to implement IDisposable interface, write cleanup code in Dispose method, and call GC.SuppressFinalize method. Its like instructing GC not to call your constructor. For more details read why is it preferred to not use finalize for clean up? in OOPS chapter.
Can we force garbage collector to run?
System.GC.Collect () forces garbage collector to run. This is not recommended but can be used if situations arise.
What is reflection?
All .NET assemblies have metadata information stored about the types defined in modules. This metadata information can be accessed by mechanism called as Reflection. System. Reflection can be used to browse through the metadata information.
Using reflection, you can also dynamically invoke methods using System.Type.Invokemember. Below is sample source code if needed you can also get this code from CD provided, go to Source code folder in Reflection Sample folder.
Public Class Form1
Private Sub Form1_Load (ByVal sender As System. Object, ByVal e as System.EventArgs) Handles MyBase.Load
Dim Pobjtype As Type
Dim PobjObject As Object
Dim PobjButtons As New Windows.Forms.Button ()
Pobjtype = PobjButtons.GetType ()
For Each PobjObject in Pobjtype.GetMembers
LstDisplay.Items.Add (PobjObject.ToString ())
Next
End Sub
End Class
Note:- Sample source code is compiled using VB.NET 2005.
Sample source code uses reflection to browse through "Button" class of "Windows.Forms". If you compile and run the program following is output as shown in "Sample Reflection Display". Using this reflection, you can also dynamically invoke a method using "System.Type.InvokeMember".
System.Type.InvokeMember is left as homework for readers.Believe me you will enjoy doing it yourself and the concept of reflection will be clearer.
What are different types of JIT?
JIT compiler is a part of the runtime execution environment.
In Microsoft .NET there are three types of JIT compilers:
* Pre-JIT: - Pre-JIT compiles complete source code into native code in a single
compilation cycle. This is done at the time of deployment of the application.
* Econo-JIT: - Econo-JIT compiles only those methods that are called at runtime.
However, these compiled methods are removed when they are not required.
* Normal-JIT: - Normal-JIT compiles only those methods that are called at runtime.
These methods are compiled the first time they are called, and then they are stored in
cache. When the same methods are called again, the compiled code from cache is used
for execution.
What are Value types and Reference types?
Value types directly contain their data that are either allocated on the stack or allocated in-line in a structure. So value types are actual data. 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. You can view reference type as pointers to actual data.
Variables that are value types each have their own copy of the data, and therefore operations on one variable do not affect other variables. Variables that are reference types can refer to the same object; therefore, operations on one variable can affect the same object referred to by another variable. All types derive from the System. Object base type.
What is concept of Boxing and Unboxing ?
Boxing and unboxing act like bridges between value type and reference types. When we convert value type to a reference type it’s termed as boxing. Unboxing is just vice-versa. When an object
box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.
Below is sample code of boxing and unboxing where integer data type are converted in to object and then vice versa.
int i = 1;object obj = i; // boxingint j = (int) obj; // unboxing What is the difference between VB.NET and C#?
Well this is the most debatable issue in .NET community and people treat languages like religion. It is a subjective matter which language is best. Some like VB.NET’s natural style and some likeprofessional and terse C# syntaxes. Both use the same framework and speed is very much equivalents. Still let us list down some major differences between them:-
Advantages VB.NET:-
* Has support for optional parameters that makes COM interoperability much easy.
* With Option Strict off late binding is supported.Legacy VB functionalities can be used by using Microsoft.VisualBasic namespace.
* Has the WITH construct which is not in C#.
* The VB.NET parts of Visual Studio .NET compiles your code in the background. While this is considered an advantage for small projects, people creating very large projects have found that the IDE slows down considerably as the project gets larger.
Advantages of C#
* XML documentation is generated from source code but this is now been incorporated in Whidbey.
* Operator overloading which is not in current VB.NET but is been introduced in Whidbey.
* Use of this statement makes unmanaged resource disposal simple.
* Access to Unsafe code. This allows pointer arithmetic etc, and can improve performance in some situations. However, it is not to be used lightly, as a lot of the normal safety of C# is lost (as the name implies).This is the major difference that you can access unmanaged code in C# and not in VB.NET.
what is the difference between System exceptions and Application exceptions?
All exception derives from Exception Base class. Exceptions can be generated programmatically or can be generated by system. Application Exception serves as the base class for all applicationspecific exception classes. It derives from Exception but does not provide any extended functionality. You should derive your custom application exceptions from Application Exception. Application exception is used when we want to define user-defined exception, while system exception is all that is defined by .NET.

(I)What is CODE Access security?
CAS is part of .NET security model that determines whether a piece of code is allowed to run and what resources it can use while running. Example CAS will allow an application to read but not to write and delete a file or a resource from a folder..
How to prevent my .NET DLL to be decompiled?
By design, .NET embeds rich Meta data inside the executable code using MSIL. Any one can easily decompile your DLL back using tools like ILDASM (owned by Microsoft) or Reflector for .NET which is a third party. Secondly, there are many third party tools, which make this decompiling process a click away. So any one can easily look in to your assemblies and reverse engineer them back in to actual source code and understand some real good logic, which can make it easy to crack your application.
The process by which you can stop this reverse engineering is using "obfuscation". It is a technique, which will foil the decompilers. Many third parties (XenoCode, Demeanor for .NET) provide .NET obfuscation solution. Microsoft includes one that is Dotfuscator Community Edition with Visual Studio.NET.
what is the difference between Convert.toString and .toString () method?
Just to give an understanding of what the above question means see the below code.
int i =0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i));
We can convert the integer "i" using "i.ToString()" or "Convert.ToString" so what is the difference. The basic difference between them is "Convert" function handles NULLS while "i.ToString()" does not it will throw a NULL reference exception error. So as a good coding practice using "convert" is always safe.
What is Native Image Generator (Ngen.exe)?
The Native Image Generator utility (Ngen.exe) allows you to run the JIT compiler on your assembly's MSIL and generate native machine code which is cached to disk. After the image is created .NET runtime will use the image to run the code rather than from the hard disk. Running Ngen.exe on an assembly potentially allows the assembly to load and execute faster, because it restores code and data structures from the native image cache rather than generating them dynamically.
Below are some points to be remembered for Native Image Generator:-
* Native images load faster than MSIL because JIT compilation and type-safety verifications is eliminated.
* If you are sharing code between process Ngen.exe improves the performance significantly. As Native image generated Windows PE file so a single DLL file can be shared across applications. By contrast JIT produced code are private to an assembly and cannot be shared.
* Native images enable code sharing between processes.
* Native images require more storage space and more time to generate.
* Startup time performance improves lot. We can get considerable gains when applications share component assemblies because after the first application has been started the shared components are already loaded for subsequent applications. If assemblies in an application must be loaded from the hard disk, does not benefit as much from native images because the hard disk access time shadows everything.
* Assemblies in GAC do not benefit from Native image generator as the loader performs extra validation on the strong named assemblies thus shadowing the benefits of Native Image Generator.
* If any of the assemblies change then Native image should also be updated.
* You should have administrative privilege for running Ngen.exe.
* While this can fasten, your application startup times as the code is statically compiled but it can be somewhat slower than the code generated dynamically by the JIT compiler. Therefore, you need to compare how the whole application performance with Ngen.exe and with out it. To run Ngen.exe, use the following command line.
ngen.exe install <assemblyname>This will synchronously precompile the specified assembly and all of its dependencies. The generated native images are stored in the native image cache.
In .NET Framework 2.0 there is a service (.NET Runtime Optimization Service) which can precompile managed assemblies in the background. You can schedule your assemblies to be precompiled asynchronously by queuing them up with the NGEN Service. Use the following command line.
Ngen.exe install <assemblyname> /queue :<priority>Assemblies, which are critical to your application’s start up time, should be precompiled either synchronously or asynchronously with priority 1. Priority 1 and 2 assemblies are precompiled aggressively while Priority 3 assemblies are only precompiled during machine idle-time. Synchronously precompiling your critical assemblies guarantees that the native images will be available prior to the first time your end user launches the application but increases the time taken to run your application's set up program.
You can uninstall an assembly and its dependencies (if no other assemblies are dependent on them) from the native image cache by running the following command.
ngen.exe uninstall <assemblyname>Native images created using Ngen.exe cannot be deployed; instead, they need to be created on the end user's machine. These commands therefore need to be issued as part of the application's setup program. Visual Studio .NET can be used to implement this behavior by defining custom actions in a Microsoft Installer (MSI) package.
Note:- One of the things the interviewer will expect to be answered is what scenario will use a Native Image generator. Best is to say that we first need to test the application performance with Native Image and with out it and then make a decision. If we see that we have considerable performance difference we can then use native image generator.
If we have two version of same assembly in GAC how do we make a choice?
OK first let us try to understand what the interviewer is talking about. Let us say you have made an application and its using a DLL which is present in GAC. Now for some reason you make second version of the same DLL and put it in GAC. Now which DLL does the application refer? Ok by default, it always uses the version by which you have compiled. However, you want that it should actually use the older version.
So first, we answer in short. You need to specify "bindingRedirect" in your config file. For instance in the below case "ClassLibraryVersion" has two versions "1.1.1830.10493" and "1.0.1830.10461" from which "1.1.1830.10493" is the recent version. However, using the bindingRedirect we can specify saying "1.0.1830.10461" is the new version. Therefore, the client will not use "1.1.1830.10493".
<Configuration>
<runtime>
<assemblyBinding xmlns="urn: schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="ClassLibraryVersion"
PublicKeyToken="b035c4774706cc72"
Culture="neutral"/>
<bindingRedirect oldVersion= "1.1.1830.10493"
NewVersion= "1.0.1830.10461"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Ok now we will try to answer it in long way by doing a small sample project. Again, this project will be done using C#. In CD you can find the "Versioning" project. Below is the solution display, it has two projects one the windows client project ("WindowsVersioningCSharp") and second the class library project ("ClassLibraryVersion") which will be installed in GAC with two versions.

Our first primary goal is to put two different versions of the same DLL in GAC. So let us make a walk through of "ClassLibraryVersion" project. It is a very simple class that has "Version" function, which just sends a string "This is old Version". Second, we will also just ensure that the assembly version is "1.0" in the "AssemblyInfo.cs".
Second, in order that we can put a DLL in GAC we need to create generate strong names and assign the same to the class. For instance, in below figure I have generated the strong name in "mykey.snk" and assigned the same to the DLL.

Finally, we need to install the same in GAC using "gacutil" tool. Below is the figure that shows the same. This installs one version of "ClassLibraryVersion.dll" in GAC.

Now it is time to create a second version of the DLL. So here is what we will do first, we will just return a different string value for this new version DLL. You can see in the below figure I have changed the string to return "This is New Version". Secondly we also need to change the AssemblyVersion to "1.1.*" in the "AssemblyInfo.cs" file. After that again compile the DLL and run the "gacutil" to register this second version of the "ClasLibraryVersion.dll".

Now when we view the GAC we can see two version of "ClassLibraryVersion" i.e. "1.1.1832.2619" and "1.0.1832.2172" (see figure below). Figure

Now that we have created the environment of two version of the same DLL in GAC its time to look at how client can make a choice between those versions. We need to generate "publicKeyToken" in order to move ahead. Below is a sample print screen, which shows how we can use "sn.exe" to generated the public key token. Note the "-T" parameter.

Now let us look at the client that will consume this DLL. I have just added windows form and a button to the same. In the button click, we will try to call the version function and display the data. Therefore, below is the code in the first step we create the object of "ClassLibraryVersion.Class1" and in the second step we call the "Version" function to display the data.

Now comes the most important part of the whole thing the "app.config" file, which will decide which version, should be used. So add a new "app.config" file in the project and add the "AssemblyBinding" section as show below. Therefore, you need to specify the following things:-
Assembly name in the "name" attribute of "assemblyIdentity" section.
* Specify the "publicKeyToken" value in the "assemblyIndentity"section which was generated using "sn.exe -T ‘dllname.dll’ ".
* Specify the "oldVersion" and "newVersion" values in the "bindingRedirect" element. So whatever version we want the client to use should be specified in the "newVersion" attribute.