Friday, October 26, 2007

Option Strict/Explicit/Compare

Option Explicit Statement (Visual Basic)
Forces explicit declaration of all variables in a file.

Option Explicit { On Off }
var ExpCollDivStr = ExpCollDivStr;
ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl039cf6c6b,";
var ExpCollImgStr = ExpCollImgStr;
ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl03img,";
Parts
On
Optional. Enables Option Explicit checking.

If On or Off is not specified, the default is On.

Off
Optional. Disables Option Explicit checking.

var ExpCollDivStr = ExpCollDivStr;
ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl043a3f538,";
var ExpCollImgStr = ExpCollImgStr;
ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl04img,";

Remarks
If used, the Option Explicit statement must appear in a file before any other source code statements.

When Option Explicit appears in a file, you must explicitly declare all variables using the Dim or ReDim statements. If you attempt to use an undeclared variable name, an error occurs at compile time.

Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear. If you do not use the Option Explicit statement, all undeclared variables are of Object type.

Note :
The compiler default is Option Explicit On if you do not specify Option Explicit in your code.
You can also set Option Explicit in the Visual Studio integrated development environment (IDE) or on a command line.

To set Option Explicit in the integrated development environment (IDE)
1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Explicit setting.

To set Option Explicit on the command line
· Include the /optionexplicit compiler option in the vbc command.
var ExpCollDivStr = ExpCollDivStr;
ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl06ecb5365,";
var ExpCollImgStr = ExpCollImgStr;
ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl06img,";

Example
The following example uses the Option Explicit statement to force explicit declaration of all variables. Attempting to use an undeclared variable causes an error at compile time.
Visual Basic
Copy Code
' Force explicit variable declaration. Option Explicit On
Visual Basic
Copy Code
Dim thisVar As Integer
thisVar = 10
' The following assignment produces a COMPILER ERROR because ' the variable is not declared and Option Explicit is On.
thisInt = 10 ' causes ERROR




Visual Basic Language Reference
Option Strict Statement

Restricts implicit data type conversions to only widening conversions.

Option Strict { On Off }
var ExpCollDivStr = ExpCollDivStr;
ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl031d087ea,";
var ExpCollImgStr = ExpCollImgStr;
ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl03img,";
Parts

On
Optional. Enables Option Strict checking.

Off
Optional. Disables Option Strict checking.

If On or Off is not specified, the default is Off.

var ExpCollDivStr = ExpCollDivStr;
ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl04b969ba9,";
var ExpCollImgStr = ExpCollImgStr;
ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl04img,";

Remarks
If used, the Option Strict statement must appear in a file before any other source code statements.

Visual Basic allows conversions of many data types to other data types. Data loss can occur when the value of one data type is converted to a data type with less precision or smaller capacity.
A run-time error occurs if such a narrowing conversion fails. Option Strict ensures compile-time notification of these narrowing conversions so they can be avoided.

In addition to disallowing implicit narrowing conversions, Option Strict generates an error for late binding. An object is late bound when it is assigned to a variable that is declared to be of type Object.

Because Option Strict On provides strong typing, prevents unintended type conversions with data loss, disallows late binding, and improves performance, its use is strongly recommended.

Note :
The compiler default is Option Strict Off if you do not specify Option Strict in your code.
You can also set Option Strict in the Visual Studio integrated development environment (IDE) or on a command line.

To set Option Strict in the integrated development environment (IDE)
1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Strict setting.

To set Option Strict on the command line
· Include the /optionstrict compiler option in the vbc command.
var ExpCollDivStr = ExpCollDivStr;
ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl060ac3ee2,";
var ExpCollImgStr = ExpCollImgStr;
ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl06img,";

Example
The following example demonstrates how the Option Strict statement disallows late binding and conversions where data would be lost.

Visual Basic
Copy Code
Option Strict On
Visual Basic
Copy Code
Dim thisVar As Integer
Dim thisObj As Object = New widget
thisVar = 1000
' Declared variable does not generate error.
' Attempting to convert Double to Integer generates a COMPILER ERROR.
thisVar = 1234567890.9876542 ' causes ERROR
' Late-bound call generates a COMPILER ERROR.
Call thisObj.Method1() ' causes ERROR





Visual Basic Language Reference
Option Compare Statement


Declares the default comparison method to use when comparing string data.

Option Compare { Binary Text }
var ExpCollDivStr = ExpCollDivStr;
ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl039e03175,";
var ExpCollImgStr = ExpCollImgStr;
ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl03img,";

Parts
Binary
Optional.
Results in string comparisons based on a sort order derived from the internal binary representations of the characters.

Text
Optional.
Results in string comparisons based on a case-insensitive text sort order determined by your system's locale.

var ExpCollDivStr = ExpCollDivStr;
ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl047019bb8,";
var ExpCollImgStr = ExpCollImgStr;
ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl04img,";

Remarks
If used, the Option Compare statement must appear in a file before any other source code statements.

The Option Compare statement specifies the string comparison method (Binary or Text) for a class, module or structure. If an Option Compare statement is not included, the default text comparison method is Binary.
In Microsoft Windows, sort order is determined by the code page. For more information, see

Code Pages.
In the following example, characters in the English/European code page (ANSI 1252) are sorted using Option Compare Binary, which produces a typical binary sort order.
A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø
When the same characters in the same code page are sorted using Option Compare Text, the following text sort order is produced.
(A=a) < (À = à) < (B=b) < (E=e) < (Ê = ê) < (Z=z) < (Ø = ø)
You can also set Option Compare in the Visual Studio integrated development environment (IDE) or on a command line.

To set Option Compare in the integrated development environment (IDE)
1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Compare setting.

To set Option Compare on the command line
· Include the /optioncompare compiler option in the vbc command.
var ExpCollDivStr = ExpCollDivStr;
ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl07878f921,";
var ExpCollImgStr = ExpCollImgStr;
ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl07img,";

Example
The following example uses the Option Compare statement to set the binary comparison as the default string comparison method.

Visual Basic
Copy Code
' Set the string comparison method to Binary ("AAA" < "aaa").

Option Compare Binary

The following example uses the Option Compare statement to set the case-insensitive text sort order as the default string comparison method.
Visual Basic
Copy Code
' Set the string comparison method to Text ("AAA" = "aaa").

Option Compare Text

Thursday, October 25, 2007

C# AND VB.NET COMPARISION

Table of Contents

1. Syntax Differences
1.1 Case Sensitivity
1.2 Statement Delimiters
1.3 Statement Blocks
1.4 Comments
1.5 Variable Declarations
1.6 Data Type Names
1.7 Special Operators
1.8 Redimensioning of Arrays
1.9 Self Documenting Code
1.10 Operator Overloading
1.11 Keywords

2. Managed and Unmanaged code
2.1 Writing Unmanaged Code
2.2 COM Interoperability

3. References


1. SYNTAX DIFFERENCES

CASE SENSITIVITY
C# is case-sensitive while VB.NET is not


STATEMENT DELIMITERS

Statement delimiters are the delimiters used to separate each statement from one another.
In C#, the semicolon is the statement delimiter. In VB.NET, each statement is delimited by a carraige return, meaning, essentially, each line of code goes on its own line.


STATEMENT BLOCKS
A block is a set of grouped statements. For example, if you have an If statement in VB.NET with the following form:
If booleanValue then
Statement1
Statement2
...
StatementN
End If
The statements Statement1 through StatmentN are all in a block. Note that the block is marked by the beginning If statement and the closing End If. In C#, curly braces are used as block delimiters. That is, in C# our if code would look like:
if (booleanValue)
{
Statement1
Statement2
...
StatementN
}

COMMENTS
In VB.NET we specify commented lines using the apostrophe ('); in C# we can have single line comments, marked by //, or we can create mutli-line comments using the delimiters /* and */. That is, everything between those delimiters is considered a comment.

VARIABLE DECLARATIONS

In VB.NET variables are declared via the Dim statement, in the following syntax:
Dim VariableName as Type [ = value]
In C#, the syntax is just a little different. We omit the Dim statement and place the Type before the VariableName, like so:
Type VariableName [ = value]; // an exampleint iAge = 23;

DATA TYPE NAMES

Differences in Data Type Names
Visual C# .NET also supports the signed byte, unsigned short, unsigned int, and unsigned long data types, which are not available in Visual Basic .NET.

Visual Basic .NET Visual C# .NET .NET Framework
Boolean bool System.Boolean
Byte byte System.Byte
Short short System.Int16
Integer int System.Int32
Long long System.Int64
Single float System.Single
Double double System.Double
Decimal decimal System.Decimal
Date System.DateTime System.DateTime
String string System.String
Char char System.Char
Object object System.Object
n/a sbyte System.Sbyte
n/a ushort System.UInt16
n/a uint System.UInt32
n/a ulong System.UInt64

SPECIAL OPERATORS
C# includes ?: (conditional assignment), ++ (increment) and – (decrement) operators.
These Operators are not available in VB.NET.

REDIMENSIONING AN ARRAY
Redim Preserve
Visual Basic.NET allows you to redimension an array while preserving the current contents using the Redim Preserve statement.This is not available in C#.

SELF DOCUMENTING CODE
C# allows you to generate HTML documentation for your code out of the comments you write inside your code file.
This feature is not available in VB.NET

OPERATOR OVERLOADING

C# Supports Operator Overloading, VB.NET doesn’t.

Struct Vector
{
public double x, y, z;
public Vector(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
public Vector(Vector rhs)
{
x = rhs.x;
y = rhs.y;
z = rhs.z;
}
public override string ToString()
{
return “(“ + x + “, “ + y “, “ + z “ )”;
}
public static Vector operator + (Vector lhs, Vector rhs)
{
Vector result = new Vector(lhs);
result.x += rhs.x;
result.y += rhs.y;
result.z += rhs.z;
return result;
}
}

// Usage
Vector vect1, vect2, vect3;
.
.
.
vect3 = vect1 + vect2;
.
.
KEYWORDS

The following table lists the keywords that Visual Basic .NET and Visual C# .NET use in several categories. This information can also be found in the Visual Studio .NET online documentation.

Purpose Visual Basic .NET Visual C# .NET

Object Oriented Programming
Indicates a class constructor Public Class Class1
Public Sub New(..)
MyBase.New

End Sub

End Class
Note: You have to call the base class constructor explicitly in Visual Basic .NET.
public class Class1
{
public Class1(..)
{

}
….
}
Note: The call to the base class constructor (base()) is generated automatically by the compiler in Visual C# .NET if you do not include constructor initializers.


Indicates a class destructor
Note: The Destructor or Finalize method is called by garbage collection.
VB.NET
Protected Overrides Sub Finalize()
m_Gadget = Nothing
m_Gear = Nothing
MyBase.Finalize()
End Sub

C#
public class Class1
{
public ~Class1()
{
….
}
}


Declares a class
C# AND VB.NET COMPARISION

Table of Contents

1. Syntax Differences
1.1 Case Sensitivity
1.2 Statement Delimiters
1.3 Statement Blocks
1.4 Comments
1.5 Variable Declarations
1.6 Data Type Names
1.7 Special Operators
1.8 Redimensioning of Arrays
1.9 Self Documenting Code
1.10 Operator Overloading
1.11 Keywords

2. Managed and Unmanaged code
2.1 Writing Unmanaged Code
2.2 COM Interoperability

3. References


1. SYNTAX DIFFERENCES

CASE SENSITIVITY
C# is case-sensitive while VB.NET is not


STATEMENT DELIMITERS

Statement delimiters are the delimiters used to separate each statement from one another.
In C#, the semicolon is the statement delimiter. In VB.NET, each statement is delimited by a carraige return, meaning, essentially, each line of code goes on its own line.


STATEMENT BLOCKS
A block is a set of grouped statements. For example, if you have an If statement in VB.NET with the following form:
If booleanValue then
Statement1
Statement2
...
StatementN
End If
The statements Statement1 through StatmentN are all in a block. Note that the block is marked by the beginning If statement and the closing End If. In C#, curly braces are used as block delimiters. That is, in C# our if code would look like:
if (booleanValue)
{
Statement1
Statement2
...
StatementN
}

COMMENTS
In VB.NET we specify commented lines using the apostrophe ('); in C# we can have single line comments, marked by //, or we can create mutli-line comments using the delimiters /* and */. That is, everything between those delimiters is considered a comment.

VARIABLE DECLARATIONS

In VB.NET variables are declared via the Dim statement, in the following syntax:
Dim VariableName as Type [ = value]
In C#, the syntax is just a little different. We omit the Dim statement and place the Type before the VariableName, like so:
Type VariableName [ = value]; // an exampleint iAge = 23;

DATA TYPE NAMES

Differences in Data Type Names
Visual C# .NET also supports the signed byte, unsigned short, unsigned int, and unsigned long data types, which are not available in Visual Basic .NET.

Visual Basic .NET
Visual C# .NET
.NET Framework
Boolean
bool
System.Boolean
Byte
byte
System.Byte
Short
short
System.Int16
Integer
int
System.Int32
Long
long
System.Int64
Single
float
System.Single
Double
double
System.Double
Decimal
decimal
System.Decimal
Date
System.DateTime
System.DateTime
String
string
System.String
Char
char
System.Char
Object
object
System.Object
n/a
sbyte
System.Sbyte
n/a
ushort
System.UInt16
n/a
uint
System.UInt32
n/a
ulong
System.UInt64

SPECIAL OPERATORS
C# includes ?: (conditional assignment), ++ (increment) and – (decrement) operators.These Operators are not available in VB.NET.

REDIMENSIONING AN ARRAY
Redim Preserve
Visual Basic.NET allows you to redimension an array while preserving the current contents using the Redim Preserve statement.This is not available in C#.

SELF DOCUMENTING CODE
C# allows you to generate HTML documentation for your code out of the comments you write inside your code file.
This feature is not available in VB.NET

OPERATOR OVERLOADING

C# Supports Operator Overloading, VB.NET doesn’t.

Struct Vector
{
public double x, y, z;
public Vector(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
public Vector(Vector rhs)
{
x = rhs.x;
y = rhs.y;
z = rhs.z;
}
public override string ToString()
{
return “(“ + x + “, “ + y “, “ + z “ )”;
}
public static Vector operator + (Vector lhs, Vector rhs)
{
Vector result = new Vector(lhs);
result.x += rhs.x;
result.y += rhs.y;
result.z += rhs.z;
return result;
}
}

// Usage
Vector vect1, vect2, vect3;
.
.
.
vect3 = vect1 + vect2;
.
.
KEYWORDS

The following table lists the keywords that Visual Basic .NET and Visual C# .NET use in several categories. This information can also be found in the Visual Studio .NET online documentation.

Purpose
Visual Basic .NET
Visual C# .NET


Object Oriented Programming




Indicates a class constructor
Public Class Class1
Public Sub New(..)
MyBase.New

End Sub

End Class
Note: You have to call the base class constructor explicitly in Visual Basic .NET.
public class Class1
{
public Class1(..)
{

}
….
}
Note: The call to the base class constructor (base()) is generated automatically by the compiler in Visual C# .NET if you do not include constructor initializers.


Indicates a class destructor
Note: The Destructor or Finalize method is called by garbage collection.
Protected Overrides Sub Finalize()
m_Gadget = Nothing
m_Gear = Nothing
MyBase.Finalize()
End Sub

public class Class1
{
public ~Class1()
{
….
}
}


Declares a class
Class
class


Indicates class inheritance
Public Class A
Inherits B

End Class
public class A : B
{

}


Indicates that the class can only be inherited and cannot be instantiated
MustInherit
abstract


Indicates that the class cannot be inherited
NotInheritable
sealed


Calls your own implementation of the method instead of an overridden method in the derived class
MyClass
None



Refers to a base class from the derived class
MyBase
base


Declares a type-safe reference to a class method
Delegate
delegate


Indicates that the method or the property overrides the implementation in its base class
Overrides
override


Indicates that these methods have no implementation and must be implemented in derived classes
MustOverride
(in MustInherit
class)
abstract
(in abstract
class)


Indicates that the method or the property cannot be overridden in derived classes
NotOverridable
Note: By default, methods are not overridable.
sealed


Indicates that the method or the property can be overridden in an inheriting class
Overridable
virtual


Overloads a procedure, a function, or a method
Overloads
None. Define functions with same name but different signatures.


Specifies that a variable can contain an object whose events you want to handle
WithEvents
No specific keyword


Specifies the events for which an event procedure will be called
Handles (Event procedures can still be associated with a WithEvents variable by naming pattern.)
n/a


Evaluates an object expression one time to access multiple members
With objExpr
<.member>
<.member>
End With
n/a


Refers to the current object
Me
This


Declares an enumerated type
Enum

End Enum
Enum


Declares an interface
Interface
interface


Implements an interface
Implements
class C1 : I1


Indicates an indexer
Default Property
public string this[int index]
{
get {return List[index];}
set {List[index]=value;}
}


Class Access Modifiers




Indicates that the modifier is accessible outside the project or the assembly
Public
public


Indicates that the modifier is accessible inside the assembly only
Friend
internal


Indicates that the modifier is accessible only in the project (for nested classes, in the enclosing class)
Private
private


Class Member Access Modifiers




Indicates that the modifier is accessible outside the class and the project
Public
public


Indicates that the modifier is accessible outside the class, but in the project
Friend
internal


Indicates that the modifier is only accessible in a class or a module
Private
private


Indicates that the modifier is accessible only to current and derived classes
Protected
protected


Indicates the union of Protected and Friend or Internal
Protected Friend
protected internal


Indicates that the members are shared across all instances
Shared
static


Miscellaneous Lifetime




Preserves the local variables for the procedure
Static
n/a


Other



Calls the Windows API
Declare statement
use Platform Invoke

Indicates a comment
‘, Rem
//, /* */ for miltine comments,
/// for XML comments

Indicates a constant
Const
Const, readonly


Creates a new object
New, CreateObject
new

Declares a function or a method with no return value
Sub
void

Declares that an object can be modified asynchronously
n/a
volatile

Declares a variable
Private, Public, Friend, Protected, Static, Shared, Dim
declarators (keywords include user-defined types and built-in types)

Declares a variable explicitly
Option Explicit
None (All variables must be declared before use)

Declares and raises an event
Event, RaiseEvent
event

Declares a structure
Structure

End Structure
struct

Defines a default property
Default
by using indexers

Declares a null object
Nothing
null

Declares a namespace
Namespace

End Namespace
Namespace
{

}

Indicates namespace usage
Imports
using

Retrieves a character from a string
GetChar Function
[ ]

Returns the address of a function
AddressOf (For class members, this operator returns a reference to a function in the form of a delegate instance)
delegate

Tests for a null object
Obj Is Nothing
obj == null

Tests for a database null expression
IsDbNull
n/a

Threads primitives
SyncLock
lock










2. MANAGED AND UNMANAGED CODE
WRITING UNMANAGED CODE
C# permits you to write unmanaged code. In unmanaged code, you can do things such as declare and operate on pointers, perform conversions between pointers and integral types, and take the address of variables. In a sense, writing unmanaged code is much like writing Visual C code in a Visual C# .NET program.
Because code that is written by using an unmanaged context cannot be verified to be safe, it is run only when the code is fully trusted. Do not use unmanaged context to try to write Visual C code in Visual C# .NET. Unmanaged code must be clearly marked with the modifier unsafe so that developers cannot use unmanaged features accidentally, and the execution engine works to make sure that unmanaged code cannot be run in a non-trusted environment. The scope of the unmanaged context extends from the parameter list to the end of the function, so pointers can also be used in the parameter list.
In Visual Basic .NET, you cannot write unmanaged code, but can call it. Please note that writing unmanaged code and calling unmanaged code are different things all together.

COM INTEROPERABILITY
.NET provides three types of interoperability with unmanaged code:
1. The ability to call a COM component from .NET
2. The ability to call a .NET component from COM and
3. The ability to call API functions from .NET.
When you call unmanaged COM components from .NET, the runtime creates a proxy component for the COM object called a runtime callable wrapper (RCW). The RCW handles all the interaction between .NET code and the COM component. When you call .NET components from COM, the runtime creates a proxy called a COM callable wrapper (CCW).
.NET uses Platform Invocation to allow .NET code to make calls to APIs, such as calls to the Windows operating system's API functions.
Since all types of COM Interoperability is handled by the CLR, it doesn’t matter whether you are using C# or VB.NET.



REFERENCES:
http://support.microsoft.com

This Document does not give a complete end-to-end comparison between C# and VB.NET. This is only meant to help developers who are moving from VB.NET to C# and vice versa.



[CodeEverywhere]
geovisit();

Class
class


Indicates class inheritance
Public Class A
Inherits B

End Class
public class A : B
{

}


Indicates that the class can only be inherited and cannot be instantiated
MustInherit
abstract


Indicates that the class cannot be inherited
NotInheritable
sealed


Calls your own implementation of the method instead of an overridden method in the derived class
MyClass
None



Refers to a base class from the derived class
MyBase
base


Declares a type-safe reference to a class method
Delegate
delegate


Indicates that the method or the property overrides the implementation in its base class
Overrides
override


Indicates that these methods have no implementation and must be implemented in derived classes
MustOverride
(in MustInherit
class)
abstract
(in abstract
class)


Indicates that the method or the property cannot be overridden in derived classes
NotOverridable
Note: By default, methods are not overridable.
sealed


Indicates that the method or the property can be overridden in an inheriting class
Overridable
virtual


Overloads a procedure, a function, or a method
Overloads
None. Define functions with same name but different signatures.


Specifies that a variable can contain an object whose events you want to handle
WithEvents
No specific keyword


Specifies the events for which an event procedure will be called
Handles (Event procedures can still be associated with a WithEvents variable by naming pattern.)
n/a


Evaluates an object expression one time to access multiple members
With objExpr
<.member>
<.member>
End With
n/a


Refers to the current object
Me
This


Declares an enumerated type
Enum

End Enum
Enum


Declares an interface
Interface
interface


Implements an interface
Implements
class C1 : I1


Indicates an indexer
Default Property
public string this[int index]
{
get {return List[index];}
set {List[index]=value;}
}


Class Access Modifiers




Indicates that the modifier is accessible outside the project or the assembly
Public
public


Indicates that the modifier is accessible inside the assembly only
Friend
internal


Indicates that the modifier is accessible only in the project (for nested classes, in the enclosing class)
Private
private


Class Member Access Modifiers




Indicates that the modifier is accessible outside the class and the project
Public
public


Indicates that the modifier is accessible outside the class, but in the project
Friend
internal


Indicates that the modifier is only accessible in a class or a module
Private
private


Indicates that the modifier is accessible only to current and derived classes
Protected
protected


Indicates the union of Protected and Friend or Internal
Protected Friend
protected internal


Indicates that the members are shared across all instances
Shared
static


Miscellaneous Lifetime




Preserves the local variables for the procedure
Static
n/a


Other



Calls the Windows API
Declare statement
use Platform Invoke

Indicates a comment
‘, Rem
//, /* */ for miltine comments,
/// for XML comments

Indicates a constant
Const
Const, readonly


Creates a new object
New, CreateObject
new

Declares a function or a method with no return value
Sub
void

Declares that an object can be modified asynchronously
n/a
volatile

Declares a variable
Private, Public, Friend, Protected, Static, Shared, Dim
declarators (keywords include user-defined types and built-in types)

Declares a variable explicitly
Option Explicit
None (All variables must be declared before use)

Declares and raises an event
Event, RaiseEvent
event

Declares a structure
Structure

End Structure
struct

Defines a default property
Default
by using indexers

Declares a null object
Nothing
null

Declares a namespace
Namespace

End Namespace
Namespace
{

}

Indicates namespace usage
Imports
using

Retrieves a character from a string
GetChar Function
[ ]

Returns the address of a function
AddressOf (For class members, this operator returns a reference to a function in the form of a delegate instance)
delegate

Tests for a null object
Obj Is Nothing
obj == null

Tests for a database null expression
IsDbNull
n/a

Threads primitives
SyncLock
lock










2. MANAGED AND UNMANAGED CODE
WRITING UNMANAGED CODE
C# permits you to write unmanaged code. In unmanaged code, you can do things such as declare and operate on pointers, perform conversions between pointers and integral types, and take the address of variables. In a sense, writing unmanaged code is much like writing Visual C code in a Visual C# .NET program.
Because code that is written by using an unmanaged context cannot be verified to be safe, it is run only when the code is fully trusted. Do not use unmanaged context to try to write Visual C code in Visual C# .NET. Unmanaged code must be clearly marked with the modifier unsafe so that developers cannot use unmanaged features accidentally, and the execution engine works to make sure that unmanaged code cannot be run in a non-trusted environment. The scope of the unmanaged context extends from the parameter list to the end of the function, so pointers can also be used in the parameter list.
In Visual Basic .NET, you cannot write unmanaged code, but can call it. Please note that writing unmanaged code and calling unmanaged code are different things all together.

COM INTEROPERABILITY
.NET provides three types of interoperability with unmanaged code:
1. The ability to call a COM component from .NET
2. The ability to call a .NET component from COM and
3. The ability to call API functions from .NET.
When you call unmanaged COM components from .NET, the runtime creates a proxy component for the COM object called a runtime callable wrapper (RCW). The RCW handles all the interaction between .NET code and the COM component. When you call .NET components from COM, the runtime creates a proxy called a COM callable wrapper (CCW).
.NET uses Platform Invocation to allow .NET code to make calls to APIs, such as calls to the Windows operating system's API functions.
Since all types of COM Interoperability is handled by the CLR, it doesn’t matter whether you are using C# or VB.NET.



REFERENCES:
http://support.microsoft.com

This Document does not give a complete end-to-end comparison between C# and VB.NET. This is only meant to help developers who are moving from VB.NET to C# and vice versa.



[CodeEverywhere]
geovisit();

Wednesday, October 24, 2007

Commands in COmmand Prompt

For more information on a specific command, type HELP command-name

1) ASSOC Displays or modifies file extension associations.
2) AT Schedules commands and programs to run on a computer.
3) ATTRIB Displays or changes file attributes.
4) BREAK Sets or clears extended CTRL+C checking.
5) CACLS Displays or modifies access control lists (ACLs) of files.
6) CALL Calls one batch program from another.
7) CD Displays the name of or changes the current directory.
8) CHCP Displays or sets the active code page number.
9) CHDIR Displays the name of or changes the current directory.
10) CHKDSK Checks a disk and displays a status report.
11) CHKNTFS Displays or modifies the checking of disk at boot time.
12) CLS Clears the screen.
13) CMD Starts a new instance of the Windows command interpreter.
14) COLOR Sets the default console foreground and background colors.
15) COMP Compares the contents of two files or sets of files.
16) COMPACT Displays or alters the compression of files on NTFS partitions.
17) CONVERT Converts FAT volumes to NTFS. You cannot convert the
18) current drive.
19) COPY Copies one or more files to another location.
20) DATE Displays or sets the date.
21) DEL Deletes one or more files.
22) DIR Displays a list of files and subdirectories in a directory.
23) DISKCOMP Compares the contents of two floppy disks.
24) DISKCOPY Copies the contents of one floppy disk to another.
25) DOSKEY Edits command lines, recalls Windows commands, and creates macros.
26) ECHO Displays messages, or turns command echoing on or off.
27) ENDLOCAL Ends localization of environment changes in a batch file.
28) ERASE Deletes one or more files.
29) EXIT Quits the CMD.EXE program (command interpreter).
30) FC Compares two files or sets of files, and displays the differences
31) between them.
32) FIND Searches for a text string in a file or files.
33) FINDSTR Searches for strings in files.
34) FOR Runs a specified command for each file in a set of files.
35) FORMAT Formats a disk for use with Windows.
36) FTYPE Displays or modifies file types used in file extension associations.
37) GOTO Directs the Windows command interpreter to a labeled line in a
38) batch program.
39) GRAFTABL Enables Windows to display an extended character set in graphics
40) mode.
41) HELP Provides Help information for Windows commands.
42) IF Performs conditional processing in batch programs.
43) LABEL Creates, changes, or deletes the volume label of a disk.
44) MD Creates a directory.
45) MKDIR Creates a directory.
46) MODE Configures a system device.
47) MORE Displays output one screen at a time.
48) MOVE Moves one or more files from one directory to another directory.
49) PATH Displays or sets a search path for executable files.
50) PAUSE Suspends processing of a batch file and displays a message.
51) POPD Restores the previous value of the current directory saved by PUSHD.
52) PRINT Prints a text file.
53) PROMPT Changes the Windows command prompt.
54) PUSHD Saves the current directory then changes it.
55) RD Removes a directory.
56) RECOVER Recovers readable information from a bad or defective disk.
57) REM Records comments (remarks) in batch files or CONFIG.SYS.
58) REN Renames a file or files.
59) RENAME Renames a file or files.
60) REPLACE Replaces files.
61) RMDIR Removes a directory.
62) SET Displays, sets, or removes Windows environment variables.
63) SETLOCAL Begins localization of environment changes in a batch file.
64) SHIFT Shifts the position of replaceable parameters in batch files.
65) SORT Sorts input.
66) START Starts a separate window to run a specified program or command.
67) SUBST Associates a path with a drive letter.
68) TIME Displays or sets the system time.
69) TITLE Sets the window title for a CMD.EXE session.
70) TREE Graphically displays the directory structure of a drive or path.
71) TYPE Displays the contents of a text file.
72) VER Displays the Windows version.
73) VERIFY Tells Windows whether to verify that your files are written
74) correctly to a disk.
75) VOL Displays a disk volume label and serial number.
76) XCOPY Copies files and directory trees.

new in .NET 2005--Partial Classes

One of the language enhancements in .NET 2.0—available in both VB.NET 2005 and C# 2.0—is support for partial classes.
In a nutshell, partial classes mean that your class definition can be split into multiple physical files.
Logically, partial classes do not make any difference to the compiler. During compile time, it simply groups all the various partial classes and treats them as a single entity.

One of the greatest benefits of partial classes is that it allows a clean separation of business logic and the user interface (in particular the code that is generated by the visual designer).

Using partial classes, the UI code can be hidden from the developer, who usually has no need to access it anyway.

Partial classes will also make debugging easier, as the code is partitioned into separate files.

In this article, I will examine the use of partial classes in more detail and discuss how Visual Studio 2005 makes use of partial classes.

Using Partial ClassesListing 1 contains two class definitions written in VB.NET,

with the second class definition starting with the partial keyword.

Both class definitions may reside in two different physical files. Functionally, Listing 1 is equivalent to Listing 2.

Listing 1'---File1.vb---
Public Class Class1
Public Sub method1()
End Sub
End Class

File2.vb
Partial Public Class Class1

Public Sub method2()
End Sub
End Class

Listing 2'---
File1.vb---
Public Class Class1
Public Sub method1()
End Sub
Public Sub method2()
End Sub
End Class

So, what are the uses for partial classes? Here are some good reasons to use partial classes:
They allow programmers on your team to work on different parts of a class without needing to share the same physical file. While this is useful for projects that involve big class files, be wary: If you find your class file getting too large, it may well signal a design fault and refactoring may be required.
The most compelling reason for using partial class is to separate your application business logic from the designer-generated code. For example, the code generated by Visual Studio 2005 for a Windows Form is kept separate from your business logic (we will discuss this in a later section). This will prevent developers from messing with the code that is used for the UI. At the same time, it will prevent you from losing your changes to the designer-generated code when you change the UI.

Author's Note: The "partial" keyword in VB.NET used to be called "expands" in pre-beta versions of Visual Studio 2005.

Examining Partial ClassesThe following code sample shows the class definition of MyClass1.

I declared all my properties in this file.

To avoid confusion, I named my class file MyClass1.Properties.vb, in order to make it obvious that this file contains a properties definition.
'---MyClass1.Properties.vb'---
one of the classes need not have the Partial keyword

Public Class MyClass1
Private pX As Integer
Private py As Integer
Property x() As Integer
Get
Return pX
End Get
Set(ByVal value As Integer)
pX = value
End Set
End Property

Property y() As Integer
Get Return py
End Get
Set(ByVal value As Integer)
py = value
End Set
End PropertyEnd Class

In another file, named MyClass1.Methods.vb, I provide the methods implementation of MyClass1. I used the Partial keyword to indicate that this definition should be combined with the original MyClass1 definition.

'---MyClass1.Methods.vb'---must have the Partial keyword

Partial Public Class MyClass1
Private py As Integer
Public Sub method1()
' implementation here
End Sub

Public Sub method3(ByVal x As Integer, ByVal y As Integer)
' implementation here
End Sub

Public Sub method2()
' implementation here
End Sub
End Class

In reality, you can mix and match properties and method definitions in any of the files, but for clarity it is a good idea to group properties definitions in one file and methods definitions in another.
The usual rules of OO apply: If there is a method1 in both files, then both method1s must have unique signatures.

The syntax of partial classes in VB.NET and C# differs slightly.

The following shows the
implementation of partial classes in C#:

// In C#, the partial keyword must
// appear in all class definitions
public partial class MyClass1
{ public MyClass1()
{
//implementation here
}
}

public partial class MyClass1
{
//implementation here
}

Besides the order in which the "partial" keyword is placed, the most significant difference is the strict enforcement of the use of the "partial" keyword in all partial classes in C#.

It is mandatory, whereas in VB.NET, not all of the partial classes have to have the "partial" keyword.
This has caused a significant amount of newsgroup discussion about the rationale for the difference.

My advice is that you should always prefix partial classes with the "partial" keyword. At least this will give you a visual clue that part of the implementation of the class lies somewhere else, and it is definitely useful when it comes to debugging. While partial classes allow you to split the definition of a class into multiple files, you cannot mix languages.

That is, all partial classes must be written in the same language. Besides using the "partial" keyword for classes, you can also use it for structures and interfaces. If your class implements multiple interfaces, it is a good idea to use partial classes to contain the implementation for each interface.

new in .NET Anonymous methods

  • Anonymous Methods (C# Programming Guide)
    In versions of C# previous to 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods.
    Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.
    By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.
    C#
    Copy Code
    // Create a delegate instance
    delegate void Del(int x);

    // Instantiate the delegate using an anonymous method
    Del d = delegate(int k) { /* ... */ };

    Ø The scope of the parameters of an anonymous method is the anonymous-method-block.

    Ø It is an error to have a jump statement, such as goto, break, or continue, inside the anonymous method block whose target is outside the block. It is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous method block whose target is inside the block.

    Ø The local variables and parameters whose scope contain an anonymous method declaration are called outer or captured variables of the anonymous method.

    Ø For example, in the following code segment, n is an outer variable:
    C#
    Copy Code
    int n = 0; Del d = delegate() { System.Console.WriteLine("Copy #:{0}", ++n); };
    Unlike local variables, the lifetime of the outer variable extends until the delegates that reference the anonymous methods are eligible for garbage collection. A reference to n is captured at the time the delegate is created.
    Ø An anonymous method cannot access the ref or out parameters of an outer scope.
    Ø No unsafe code can be accessed within the anonymous-method-block.
    Example
    The following example demonstrates the two ways of instantiating a delegate:
    Associating the delegate with an anonymous method.
    Associating the delegate with a named method (DoWork).
    In each case, a message is displayed when the delegate is invoked.
    C#
    Copy Code
    // Declare a delegate
    delegate void Printer(string s);
    class TestClass { static void Main() {
    // Instatiate the delegate type using an anonymous method:
    Printer p = delegate(string j)
    {
    System.Console.WriteLine(j);
    };
    // Results from the anonymous delegate call:
    p("The delegate using the anonymous method is called.");
    // The delegate instantiation using a named method "DoWork":
    p = new Printer(TestClass.DoWork);
    // Results from the old style delegate call:
    p("The delegate using the named method is called.");
    }
    // The method associated with the named delegate:
    static void DoWork(string k)
    {
    System.Console.WriteLine(k);
    }
    }
    var ExpCollDivStr = ExpCollDivStr;
    ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl22ba5ee29,";
    var ExpCollImgStr = ExpCollImgStr;
    ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl22img,";
    Output
    The delegate using the anonymous method is called.
    The delegate using the named method is called.

Introduction of Delegates1

Ø http://www.akadia.com/services/dotnet_delegates_and_events.html

Ø Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

Ø Sometimes, however, we don't want to call a function directly - we'd like to be able to pass it to somebody else so that they can call it. This is especially useful in an event-driven system such as a graphical user interface, when I want some code to be executed when the user clicks on a button, or when I want to log some information but can't specify how it is logged.

Ø An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.

Ø The signature of a single cast delegate is shown below:
delegate result-type identifier ([parameters]);
where:
Ø result-type: The result type, which matches the return type of the function.
Ø identifier: The delegate name.
Ø parameters: The Parameters, that the function takes.

Examples:
public delegate void SimpleDelegate ()

This declaration defines a delegate named SimpleDelegate, which will encapsulate any method that takesno parameters and returns no value.

public delegate int ButtonClickHandler (object obj1, object obj2)

This declaration defines a delegate named ButtonClickHandler, which will encapsulate any method that takestwo objects as parameters and returns an int.

Ø A delegate will allow us to specify what the function we'll be calling looks like without having to specify which function to call.
Ø The declaration for a delegate looks just like the declaration for a function, except that in this case, we're declaring the signature of functions that this delegate can reference.
Ø There are three steps in defining and using delegates:

Ø Declaration
Ø Instantiation
Ø Invocation

Ø A very basic example (SimpleDelegate1.cs):
using System;
namespace Akadia.BasicDelegate
{
// Declaration
public delegate void SimpleDelegate();
class TestDelegate
{
public static void MyFunc()
{
Console.WriteLine("I was called by delegate ...");
}
public static void Main()
{
// Instantiation
SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);
// Invocation
simpleDelegate();
}
}
}
_______________________________________________________
public delegate [return type] [Delegate Name] ( [list of parameters] );

Ø where [return type] is the return type of the function, [Delegate Name] is the name of this delegate, and [List of parameters] is the list of the parameters in the function you want to point to.
Ø Delegates do differ from the C/C++ concept of function pointers. Here are some of the differences:
Ø Runtime Instantiation vs Static InstantiationDelegates are dynamic structures and are declared at runtime. In C/C++ you needed to know the function ahead of time before you can use the function pointers. In C#, delegates require runtime instantiation. This allows you the opportunity to not only using static methods but methods in class instances as well.
Ø ChainingDelegates don't just point to a single function. Rather they can be thought of as an ordered set of functions where each function in the set as the same function footprint (same return type and same number and types of parameters).]
1.
publid delegate void printFuncs (String name);
public void printToScreen(String name) { ... }
public void printToComPort(String name) { ... }
public void printToPrinter(String name) { ... }
public void dbQuery()
{
printFuncs print = new printFuncs(printToScreen);

print += new printFuncs(printToComPort);
print += new printFuncs(printToPrinter);
print("Naveen");}

2.
In this example, when you execute the delegate variable print it will in turn call printToScreen, printToComPort, and printToPrinter.NOTE: The order in which you add these functions is important. In the print example above, when delegate variable print is execute, printToScreen will be called first, then printToComPort, then printToPrinter. The functions will not be called in any other order. Also note that if any function in the chain throws an exception, the rest of the chain will not be executed.
Ø http://search.msdn.microsoft.com/search/Default.aspx?brand=msdn&locale=en-us&query=delegates
Ø Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate.
Ø This ability to refer to a method as a parameter makes delegates ideal for defining callback methods.
Ø Delegates have the following properties:
Ø Delegates are similar to C++ function pointers, but are type safe.
Ø Delegates allow methods to be passed as parameters.
Ø Delegates can be used to define callback methods.
Ø Delegates can be chained together; for example, multiple methods can be called on a single event.
Ø Methods don't need to match the delegate signature exactly. For more information, see Covariance and Contravariance
Ø C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.
Ø A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++.
Ø Unlike C function pointers, delegates are object-oriented, type safe, and secure
Ø A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with an anonymous Method.
Ø Once a delegate is instantiated, a method call made to the delegate will be passed by the delegate to that method. The parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method is returned to the caller by the delegate. This is known as invoking the delegate.
Ø An instantiated delegate can be invoked as if it were the wrapped method itself.
Ø Delegate types are derived from the Delegate class in the .NET Framework.
Ø Delegate types are sealed—they cannot be derived from— and it is not possible to derive custom classes from Delegate.
Ø Because the instantiated delegate is an object, it can be passed as a parameter, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time. This is known as an asynchronous callback, and is a common method of notifying a caller when a long process has completed.
Ø When a delegate is used in this fashion, the code using the delegate does not need any knowledge of the implementation of the method being used. The functionality is similar to the encapsulation interfaces provide.

When to Use Delegates Instead of Interfaces (C# Programming Guide)


Both delegates and interfaces allow a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct; a delegate can created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object with no knowledge of the class that implements the interface or delegate method. Given these similarities, when should a class designer use a delegate and when should they use an interface?
Use a delegate when:
An eventing design pattern is used.
It is desirable to encapsulate a static method.
The caller has no need access other properties, methods, or interfaces on the object implementing the method.
Easy composition is desired.
A class may need more than one implementation of the method.


Use an interface when:

There are a group of related methods that may be called.
A class only needs one implementation of the method.
The class using the interface will want to cast that interface to other interface or class types.

The method being implemented is linked to the type or identity of the class:
for example, comparison methods.
One good example of using a single-method interface instead of a delegate is IComparable or IComparable. IComparable declares the CompareTo method, which returns an integer specifying a less than, equal to, or greater than relationship between two objects of the same type. IComparable can be used as the basis of a sort algorithm, and while using a delegate comparison method as the basis of a sort algorithm would be valid, it is not ideal. Because the ability to compare belongs to the class, and the comparison algorithm doesn’t change at run-time, a single-method interface is ideal.