Tuesday, May 11, 2010

Value Types and Reference Types

Value Types
  • Allocated on the stack.
  • Value type variables are local copies.
  • Value types are deived from System.ValueType
  • Values types are always sealed and cannot be extended.
  • Variables are passed by value( copy of the variable is passed into the called function )
  • Value types are never placed onto the heap and therefore do not need to be finalized.
  • The variable of this type die when they fall out of the defining scope.
Reference Types
  • Allocated on the managed heap
  • Reference type variables are pointing to the memory occupied by the allocated instance
  • Variables are passed by reference( address of the variable is passed to the called function )
  • The variable of this type die when they are garbage collected.
Nullable Types
Value types can never be assigned the value of null.


the ? suffix notation is a shorthand for creating an instance of the generic System.Nullable structure type.
?? operator allows o assign a value to a nullable type if the retrieved value is in fact null.




 

Monday, May 10, 2010

The very basic C#

A Simple C# Program
C# demands that all program logic be contained within a type definition. As explained earlier type is a general term referring to a class, interface, structure, enumeration or a delegate. In C# it is not possible to create global functions or global points of data, all data members and methods must be contained within a type definition.
A Sample C# program looks like,

Every executable C# application (console program, Windows desktop program, or Windows service) must contain a class defining a Main() method, which is used to signify the entry point of the application. The class that defines the Main() method is termed the application object. Note that the signature of Main() is decoreted with the static keyword, so it is scoped to the class level (rather than the object level) and can thus be invoked without the need to first create a new class instance. The method has a parameter, Main ( string[] args ) this parameter may contain any number of incoming command-line arguments.
Few Miscellaneous things
Strings Are Immutable
Once we assign a string object with its initial value, the character data cannot be changed. Also assigning a value to a string object results in a new string object.
But the StringBuilder in System.Text namespace modifying the object’s internal character data (and is thus more efficient), not obtaining a copy of the data in a modified format.
Type casting
eg:
byte myByte = 0;
int myInt = 200;
myByte = myInt;
When we wish to inform the compiler than we are willing to deal with a possible loss of data, we must apply an explicit cast using the C# casting operator () otherwise the following compiler error will occur
"Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)"
checked and unchecked keywords
To handle overflow or underflow conditions in the application, C# provides keywords checked and unchecked. The default behavior of the .NET runtime is to ignore arithmetic overflow. When selectively handle discrete statements, make use of the checked keyword. If you wish to trap overflow errors throughout your application, enable the /checked flag. Finally, the unchecked keyword may be used if we have a block of code where overflow is acceptable (and thus should not trigger a runtime exception).
When we wrap a statement (or a block of statements) within the scope of the checked keyword, the C# compiler emits additional CIL instructions that test for overflow conditions that may result when adding, multiplying, subtracting, or dividing two numerical data types. If an overflow has occurred, you will receive a runtime exception (System.OverflowException to be exact).

System.Convert provides a language-neutral manner to convert between data types.
The out Modifier
Output parameters must be assigned by the method being called (and therefore are passed by reference). If the called method fails to assign output parameters, you are issued a compiler error. it allows the caller to obtain multiple return values from a single method invocation.
The ref Modifier
The value is initially assigned by the caller and may be optionally reassigned by the called method (as the data is also passed by reference). No compiler error is generated if the called method fails to assign a ref parameter.
Output parameters do not need to be initialized before they passed to the method. The reason for this is the method must assign output parameters before exiting. Reference parameters must be initialized before they are passed to the method. The reason for this is we are passing a reference to an existing variable. If we don’t assign it to an initial value, that would be the equivalent of operating on an unassigned local variable.
The params Modifier
This parameter modifier allows to send in a variable number of arguments as a single logical parameter. A method can have only a single params modifier, and it must be the final parameter of the method.
eg:
double CalculateAverage(params double[] values)
{

}
double average;
average = CalculateAverage(4.0, 3.2, 5.7, 64.22, 87.2);
double[] data = { 4.0, 3.2, 5.7 };
average = CalculateAverage(data);
Array Manipulation in C#

Tuesday, May 4, 2010

A quick rundown and FAQs

A quick rundown

From the previous posts we got an overview of what is .NET, the advantages of using .NET, the bulding blocks of .NET, and we came across to a runtime execution engine (mscoree.dll) and base class library(mscorlib.dll), common language runtime (CLR), Assemblies, Single file, multi file and Satellite assemblies, Then we have seen that, assemblies contain CIL instructions (in addition to type metadata and the assembly manifest) that are compiled to platform-specific instructions using a just-in-time (JIT) compiler. In addition, we explored the role of the Common Language Specification (CLS) and Common Type System (CTS).

Frequently Asked Questions

What is .NET ?

Whar are the advantages of using .NET ?

What are the building blocks of .NET ?

What is CLR, CTS, CLS and BCL ?

What is an assembly ?

What is MSIL ?

What is metadata in an assembly ?

What is Assembly manifest ?

What is Single file, Multi file and Satellite assemby ?

What is CLR ? What are the main responsibilities of CLR ?

What is JIT ?

What is mscoree.dll and mscorlib.dll ?

Sunday, May 2, 2010

More about the building blocks of .NET Framework

The Common Language Runtime
The Common Language Runtime (CLR) is an Execution Environment . It works as a layer between Operating Systems and the applications written in .Net languages .
The core of the CLR is physically represented by a library named mscoree.dll ( Common Object Runtime Execution Engine). When an assembly is referenced for use, mscoree.dll is loaded automatically, which in turn loads the required assembly into memory. The runtime engine is responsible for a number of tasks, resolving the location of an assembly and finding the requested type within the binary by reading the contained metadata.
The CLR then lays out the type in memory, compiles the associated CIL into platformspecific instructions, performs any necessary security checks, and then executes the code.
To enable the runtime to provide services to managed code, language compilers must emit metadata that describes the types, members, and references in your code. Metadata is stored with the code; every loadable common language runtime portable executable (PE) file contains metadata. The runtime uses metadata to locate and load classes, lay out instances in memory, resolve method invocations, generate native code, enforce security, and set run-time context boundaries.
In addition to loading custom assemblies and creating custom types, the CLR will also interact with the types contained within the .NET base class libraries when required. Although the entire base class library has been broken into a number of discrete assemblies, the key assembly is mscorlib.dll. mscorlib.dll contains a large number of core types that encapsulate a wide variety of common programming tasks as well as the core data types used by all .NET languages.


Common Type System
In .NET, type is simply a general term used to refer to a class, interface, structure, enumeration, delegate. The CTS specification fully describes all possible data types and programming constructs supported by the runtime, specifies how these entities can interact with each other, and details how they are represented in the .NET metadata format.
CTS Class Types
a class type, which is the cornerstone of object-oriented programming(OOP). In C#, classes are declared using the class keyword
// A C# class type.
class Calc
{
      public int Add(int x, int y)
     {
           return x + y;
     }
}
CTS Class Characteristics
  • Is the class “sealed” or not? Sealed classes cannot function as a base class to other classes.
  • Does the class implement any interfaces? An interface is a collection of abstract members that provide a contract between the object and object user. The CTS allows a class or structure to implement any number of interfaces.
  • Is the class abstract or concrete? Abstract classes cannot be directly created, but are intended to define common behaviors for derived types. Concrete classes can be created directly.
  • What is the “visibility” of this class? Each class must be configured with a visibility attribute. Basically, this trait defines whether the class may be used by external assemblies or only from within the defining assembly
CTS Interface Types
Interface is a named collection of abstract member definitions.In C#, interface types are defined using the interface keyword.

// A C# interface type is usually declared as public, to allow types in other
// assemblies to implement their behavior.
public interface IDraw
{
         void Draw();
}

CTS Structure Types

A structure can be thought of as a lightweight class type having value-based semantics. In C# structures are defined using struct keyword.
// A C# structure type.
struct Point
{
          // Structures can contain fields.
          public int xPos, yPos;
         // Structures can contain constructors.
         public Point(int x, int y)
         {
                   xPos = x;
                   yPos = y;
         }
         // Structures may define methods.
          public void Display()
          {
                    Console.WriteLine("({0}, {1}", xPos, yPos);
          }
}
CTS Enumeration Types
Enumerations are handy programming constructs that allow you to group name/value pairs.
// A C# enumeration type.
enum CharacterType
{
          Wizard = 100,
          Fighter = 200,
          Thief = 300
}
CTS Delegate Types
Delegates are the .NET equivalent of a type-safe C-style function pointer. The key difference is that a .NET delegate is a class that derives from System.MulticastDelegate, rather than a simple pointer to a raw memory address. In C#, delegates are declared using the delegate keyword
// This C# delegate type can "point to" any method
// returning an integer and taking two integers as input.
delegate int BinaryOp(int x, int y);

CTS Type Members
A type member is constructor, finalizer, static constructor, nested type, operator, method, property, indexer, field, read-only field, constant, event.

Intrinsic CTS Data Types

All language keywords ultimately resolve to the same type defined in an assembly named mscorlib.dll.

Common Language Specification

The CLS is a set of rules that describe in vivid detail the minimal and complete set of features a given .NET-aware compiler must support to produce code that can be hosted by the CLR. CLS can be viewed as a subset of the full functionality defined by the CTS. The CLS is ultimately a set of rules that compiler builders must conform to, if they intend their products to function seamlessly within the .NET universe.
Ensuring CLS Compliance
// Tell the C# compiler to check for CLS compliance.
[assembly: System.CLSCompliant(true)]

The Intermediate Language Disassembler utility (ildasm.exe), allows us to load up any .NET assembly and investigate its contents, including the associated manifest, CIL code, and type metadata.

Saturday, May 1, 2010

Introduction to .NET

The .NET Solution
.NET Framework is a new model for developing applications in windows plaforms. Its a set of tools and libraries that enables developers to build applications much faster and easier.The main advantantages are
  • Interoperability with existing code: Existing COM binaries and C based libraries can interop with newer .NET binaries.
  • Complete and total language integration: .NET supports cross-language inheritance, crosslanguage exception handling, and cross-language debugging of code.
  • A common runtime engine for all .net languages
  •  A comprehensive base class library
  • Simplified deployment model: there is no need to register a binary unit into the system registry. .NET allows multiple versions of the same *.dll to exist in harmony on a single machine.
Building Blocks of the .NET Platform
  1. CLR :  The primary role of the Common Language Runtime is to locate, load, and manage .NET types on your behalf. The CLR also takes care of a number of low-level details such as
                      Memory management
                      Thread management
                      Exception handling
                      Garbage collection
                      Security
  2. CTS :Common Type System specification fully describes all possible data types and programming constructs supported by the runtime, specifies how these entities can interact with each other, and details how they are represented in the .NET metadata format
  3. CLS : Common Language Specification  is a related specification that defines a subset of common types and programming constructs that all .NET programming languages can agree on.
  4. In addition to the CLR and CTS/CLS specifications, the .NET platform provides a base class library that is available to all .NET programming languages. .NET includes the BCL in order to encapsulate a large number of common functions, such as file reading and writing, graphic rendering, database interaction, and XML document manipulation, which makes the programmer's job easier.
An Overview of .NET Assemblies
.NET assembly is just the .EXE or .DLL files that are the end result of your program. Perhaps most important, .NET binaries do not contain platformspecific instructions, but rather platform-agnostic intermediate language (IL) and type metadata.

Common Intermediate Language

CIL is a language that sits above any particular platform-specific instruction set. each .NET-aware compiler produces nearly identical CIL instructions. Therefore, all languages are able to interact within a well-defined binary arena. Due to the fact that assemblies contain CIL instructions, rather than platform-specific instructions, CIL code must be compiled on the fly before use. The entity that compiles CIL code into meaningful CPU instructions is termed a just-in-time (JIT) compiler, which sometimes goes by the friendly name of Jitter. The .NET runtime environment leverages a JIT compiler for each CPU targeting the runtime, each optimized for the underlying platform.
.NET Type Metadata
In addition to CIL instructions, a .NET assembly contains full, complete, and accurate metadata, which describes each and every type (class, structure, enumeration, and so forth) defined in the binary, as well as the members of each type (properties, methods, events, and so on).
Assembly Manifest
Last but not least, remember that a .NET assembly also contains metadata that describes the assembly itself (technically termed a manifest). Among other details, the manifest documents all external assemblies required by the current assembly to function correctly, the assembly’s version number, copyright information, and so forth.

 
Developers using the CLR write code in a language such as C# or VB.NET. At compile time, a .NET compiler converts such code into CIL code. At runtime, the CLR's just-in-time compiler converts the CIL code into code native to the operating system. Alternatively, the CIL code can be compiled to native code in a separate step prior to runtime by using the Native Image Generator (NGEN). This speeds up all later runs of the software as the CIL-to-native compilation is no longer necessary.



Single-File and Multifile Assemblies

If an assembly is composed of a single *.dll or *.exe module, we have a single-file assembly. Single-file assemblies contain all the necessary CIL, metadata, and associated manifest

Multifile assemblies, on the other hand, are composed of numerous .NET binaries, each of which is termed a module. When building a multifile assembly, one of these modules (termed the primary module) must contain the assembly manifest (and possibly CIL instructions and metadata for various types). The other related modules contain a module-level manifest, CIL, and type metadata. The primary module contains the set of required secondary modules within the assembly manifest.
Satellite assemblies
A .NET Framework assembly containing resources specific to a given language. Using satellite assemblies, we can place the resources for different languages in different assemblies, and the correct assembly is loaded into memory only if the user elects to view the application in that language.