.NET Framework Q&A

Introduction

Here we are discussing few common .NET frequently asked questions and answers.

The differences between the Dispose() and Finalize()

CLR uses the Dispose and Finalize methods to perform garbage collection of run-time objects of .NET applications.

The Finalize method is called automatically by the runtime. CLR has a garbage collector (GC), which periodically checks for objects in heap that are no longer referenced by any object or program. It calls the Finalize method to free the memory used by such objects.

The Dispose method is called by the programmer.Dispose is another method to release the memory used by an object. The Dispose method needs to be explicitly called in code to dereference an object from the heap. The Dispose method can be invoked only by the classes that implement the IDisposable interface.

What is code access security (CAS)?

Code access security (CAS) is part of the .NET security model that prevents unauthorized access of resources and operations, and restricts the code to perform particular tasks.

How can you turn-on and turn-off CAS?                                                                                     

You can use the Code Access Security Tool (Caspol.exe) to turn security on and off.

To turn off security, type the following command at the command prompt:

caspol -security off

To turn on security, type the following command at the command prompt:

caspol -security on

In the .NET Framework 4.0, for using Caspol.exe, you first need to set the <LegacyCasPolicy> element to true.

Differences between managed and unmanaged code

Managed code is the code that is executed directly by the CLR instead of the operating system. The code compiler first compiles the managed code to intermediate language (IL) code, also called as MSIL code. This code doesn’t depend on machine configurations and can be executed on different machines.

Unmanaged code is the code that is executed directly by the operating system outside the CLR environment. It is directly compiled to native machine code which depends on the machine configuration.

In the managed code, since the execution of the code is governed by CLR, the runtime provides different services, such as garbage collection, type checking, exception handling, and security support. These services help provide uniformity in platform and language-independent behavior of managed code applications. In the unmanaged code, the allocation of memory, type safety, and security is required to be taken care of by the developer. If the unmanaged code is not properly handled, it may result in memory leak. Examples of unmanaged code are ActiveX components and Win32 APIs that execute beyond the scope of native CLR.

What are tuples?                                                                                                                      

 Tuple is a fixed-size collection that can have elements of either same or different data types.  Similar to arrays, a user must have to specify the size of a tuple at the time of declaration.

Tuples are allowed to hold up from 1 to 8 elements and if there are more than 8 elements, then the 8th element can be defined as another tuple.

Tuples can be specified as parameter or return type of a method.

What is garbage collection? What is the difference between garbage collections in .NET 4.0 and earlier versions.                                                                                                     

Garbage collection prevents memory leaks during execution of programs.

Garbage collector is a low-priority process that manages the allocation and deallocation of memory for your application. It checks for the unreferenced variables and objects. If GC finds any object that is no longer used by the application, it frees up the memory from that object.

GC has changed a bit with the introduction of .NET 4.0. In .NET 4.0, the GC.Collect() method contains the following overloaded methods:

GC.Collect(int)
GC.Collect(int, GCCollectionMode)

Another new feature introduced in .NET is to notify you when the GC.Collect() method is invoked and completed successfully by using different methods.  .NET 4.0 supports a new background garbage collection that replaces the concurrent garbage collection used in earlier versions.        This concurrent GC allocates memory while running and uses current segment (which is 16 MB on a workstation) for that. After that, all threads are suspended. In case of background GC, a separate ephemeral GC – gen0 and gen1 can be started, while the full GC – gen0, 1, and 2 – is already running.      

How does CAS works?

There are two key concepts of CAS security policy- code groups and permissions. A code group contains assemblies in it in a manner that each .NET assembly is related to a particular code group and some permissions are granted to each code group. For example, using the default security policy, a control downloaded from a Web site belongs to the Zone, Internet code group, which adheres to the permissions defined by the named permission set. (Normally, the named permission set represents a very restrictive range of permissions.)

Assembly execution involves the following steps:

  1. Evidences are gathered about assembly.
  2. Depending on the gathered evidences, the assembly is assigned to a code group.
  3. Security rights are allocated to the assembly, depending on the code group.
  4. Assembly runs as per the rights assigned to it.

What is difference between NameSpace and Assembly?

Following are the differences between namespace and assembly:

  • Assembly is physical grouping of logical units, Namespace, logically groups classes.
  • Namespace can span multiple assemblies                                                                                                                                                               

Mention the execution process for managed code.

A piece of managed code is executed as follows:

  • Choosing a language compiler
  • Compiling the code to MSIL
  • Compiling MSIL to native code
  • Executing the code.

What is the difference between LINQ Query syntax and Method syntax ?

1. Query expression must be translated into method syntax at the compiled time (deferred execution), but Method expressions get called immediately.

2. Query syntax is more readable and concise than the Method syntax.

3. Not every  LINQ operator is available in Query syntax

What is a Function predicate?

A predicate is a function that returns true or false.

A predicate delegate is a reference to a predicate.

So basically a predicate delegate is a reference to a function that returns true or false. Predicates are very useful for filtering a list of values. 

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
    	List<int> list = new List<int> { 1, 2, 3 };

    	Predicate<int> predicate = new Predicate<int>(greaterThanTwo);

    	List<int> newList = list.FindAll(predicate);
    }

    static bool greaterThanTwo(int arg)
    {
    	return arg > 2;
    }
}

What is a  Action, Func and  Predicate?

Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.

Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or refence).

Predicate is a special kind of Func often used for comparisons, returning a boolean.

Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.

Here is a small example for Action and Func without using Linq:

class Program
{
    static void Main(string[] args)
    {
        Action<int> myAction = new Action<int>(DoSomething);
        myAction.Invoke(123);           // Prints out "123"

        Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
        Console.WriteLine(myFunc(5));   // Prints out "2.5"
    }

    static void DoSomething(int i)
    {
        Console.WriteLine(i);
    }

    static double CalculateSomething(int i)
    {
        return (double)i/2;
    }
}

What is a Delegate ?

Object-oriented , type-safe function pointer.

Delegates the responsibility for an operation to another function.

Defined with:

  • A named method
  • A delegate expression
  • A lambda expression (Unnamed, inline function)

Be first to comment

Leave a Reply