November 05, 2006
VB.NET and C# Code Syntax
Generally if we are working on multiple projects that have to use differenet languages like VB.NET and C#, most of the time it's very difficult to remember all the syntax changes in those languages. Here i have added the vb.net and c# syntax formats. Hope that it will be useful.VB.NET
Dim x As Integer
Dim s As String
Dim s1, s2 As String
Dim o 'Implicitly Object
Dim obj As New Object()
Public name As String
C#
int x;
String s;
String s1, s2;
Object o;
Object obj = new Object();
public String name;
Constants
VB.NET
Const MAX_STUDENTS As Integer = 25
' Can set to a const or var; may be initialized in a constructor
ReadOnly MIN_DIAMETER As Single = 4.93
C#
const int MAX_STUDENTS = 25;
// Can set to a const or var; may be initialized in a constructor
readonly float MIN_DIAMETER = 4.93f;
Statements
VB.NET
C#
Response.Write("foo");
Comments
' This is a comment
' This
' is
' a
' multiline
' comment
C#
// This is a comment
/*
This
is
a
multiline
comment
*/
VB.NET
Dim s, value As String
s = Request.QueryString("Name")
value = Request.Cookies("Key").Value
'Note that default non-indexed properties
'must be explicitly named in VB.NET
C#
String s = Request.QueryString["Name"];
String value = Request.Cookies["key"];
VB.NET
' Default Indexed Property
Public Default ReadOnly Property DefaultProperty(Name As String) As String
Get
Return CStr(lookuptable(name))
End Get
End Property
C#
// Default Indexed Property
public String this[String name] {
get {
return (String) lookuptable[name];
}
}
Declaring Simple Properties
VB.NET
Public Property Name As String
Get
...
Return ...
End Get
Set
... = Value
End Set
End Property
ex:
Private _size As Integer
Public Property Size() As Integer
Get
Return _size
End Get
Set (ByVal Value As Integer)
If Value < 0 Then
_size = 0
Else
_size = Value
End If
End Set
End Property
foo.Size += 1
C#
public String name {
get {
...
return ...;
}
set {
... = value;
}
}
ex:
private int _size;
public int Size {
get {
return _size;
}
set {
if (value < 0)
_size = 0;
else
_size = value;
}
}
foo.Size++;
Declare and Use an Enumeration
VB.NET
' Declare the Enumeration
Public Enum MessageSize
Small = 0
Medium = 1
Large = 2
End Enum
' Create a Field or Property
Public MsgSize As MessageSize
' Assign to the property using the Enumeration values
MsgSize = small
C#
// Declare the Enumeration
public enum MessageSize {
Small = 0,
Medium = 1,
Large = 2
}
// Create a Field or Property
public MessageSize msgsize;
// Assign to the property using the Enumeration values
msgsize = Small;
Enumerating a Collection
VB.NET
Dim S As String
For Each S In Coll
...
Next
' Array or collection looping
Dim names As String() = {"Fred", "Sue", "Barney"}
For Each s As String In names
Response.write(s)
Next
C#
foreach ( String s in coll ) {
...
}
// Array or collection looping
string[] names = {"Fred", "Sue", "Barney"};
foreach (string s in names)
Response.Write(s);
Declare and Use Methods
VB.NET
' Declare a void return function
Sub VoidFunction()
...
End Sub
' Declare a function that returns a value
Function StringFunction() As String
...
Return CStr(val)
End Function
' Declare a function that takes and returns values
Function ParmFunction(a As String, b As String) As String
...
Return CStr(A & B )
End Function
' Use the Functions
VoidFunction()
Dim s1 As String = StringFunction()
Dim s2 As String = ParmFunction("Hello", "World!")
C#
// Declare a void return function
void voidfunction() {
...
}
// Declare a function that returns a value
String stringfunction() {
...
return (String) val;
}
// Declare a function that takes and returns values
String parmfunction(String a, String b) {
...
return (String) (a + b);
}
// Use the Functions
voidfunction();
String s1 = stringfunction();
String s2 = parmfunction("Hello", "World!");
Custom Attributes
VB.NET
' Stand-alone attribute
<STAThread>
' Attribute with parameters
<DllImport("ADVAPI32.DLL")>
' Attribute with named parameters
<DllImport("KERNEL32.DLL", CharSet:=CharSet.Auto)>
C#
// Stand-alone attribute
[STAThread]
// Attribute with parameters
[DllImport("ADVAPI32.DLL")]
// Attribute with named parameters
[DllImport("KERNEL32.DLL", CharSet=CharSet.Auto)]
Arrays
VB.NET
Dim a(2) As String
a(0) = "1"
a(1) = "2"
a(2) = "3"
Dim a(2,2) As String
a(0,0) = "1"
a(1,0) = "2"
a(2,0) = "3"
C#
String[] a = new String[3];
a[0] = "1";
a[1] = "2";
a[2] = "3";
String[][] a = new String[3][3];
a[0][0] = "1";
a[1][0] = "2";
a[2][0] = "3";
VB.NET
Dim s As String = "Hello World"
Dim i As Integer = 1
Dim a() As Double = { 3.00, 4.00, 5.00 }
C#
String s = "Hello World";
int i = 1;
double[] a = { 3.00, 4.00, 5.00 };
VB.NET
If Not (Request.QueryString = Nothing)
...
End If
greeting = IIf(age < 20, "What's up?", "Hello")
C#
if (Request.QueryString != null) {
...
}
greeting = age < 20 ? "What's up?" : "Hello";
Case Statements
VB.NET
Select Case FirstName
Case "John"
...
Case "Paul"
...
Case "Ringo"
...
Case Else
...
End Select
C#
switch (FirstName) {
case "John" :
...
break;
case "Paul" :
...
break;
case "Ringo" :
...
break;
default:
...
break;
}
For Loops
VB.NET
Dim I As Integer
For I = 0 To 2
a(I) = "test"
Next
C#
for (int i=0; i<3; i++)
a(i) = "test";
While Loops
VB.NET
Dim I As Integer
I = 0
Do While I < 3
Response.write(I.ToString())
I += 1
C#
int i = 0;
while (i<3) {
Response.Write(i.ToString());
i += 1;
}
Exception Handling
VB.NET
Try
' Code that throws exceptions
Catch E As OverflowException
' Catch a specific exception
Catch E As Exception
' Catch the generic exceptions
Finally
' Execute some cleanup code
End Try
C#
try {
// Code that throws exceptions
} catch(OverflowException e) {
// Catch a specific exception
} catch(Exception e) {
// Catch the generic exceptions
} finally {
// Execute some cleanup code
}
String Concatenation
VB.NET
' Using Strings
Dim s1, s2 As String
s2 = "hello"
s2 &= " world"
s1 = s2 & " !!!"
' Using StringBuilder class for performance
Dim s3 As New StringBuilder()
s3.Append("hello")
s3.Append(" world")
s3.Append(" !!!")
C#
// Using Strings
String s1;
String s2 = "hello";
s2 += " world";
s1 = s2 + " !!!";
// Using StringBuilder class for performance
StringBuilder s3 = new StringBuilder();
s3.Append("hello");
s3.Append(" world");
s3.Append(" !!!");
Event Handler Delegates
VB.NET
Sub MyButton_Click(Sender As Object, E As EventArgs)
...
End Sub
C#
void MyButton_Click(Object sender, EventArgs E) {
...
}
Declare Events
VB.NET
' Create a public event
Public Event MyEvent(Sender as Object, E as EventArgs)
' Create a method for firing the event
Protected Sub OnMyEvent(E As EventArgs)
RaiseEvent MyEvent(Me, E)
End Sub
C#
// Create a public event
public event EventHandler MyEvent;
// Create a method for firing the event
protected void OnMyEvent(EventArgs e) {
MyEvent(this, e);
}
Add or Remove Event Handlers to Events
VB.NET
AddHandler Control.Change, AddressOf Me.ChangeEventHandler
RemoveHandler Control.Change, AddressOf Me.ChangeEventHandler
C#
Control.Change += new EventHandler(this.ChangeEventHandler);
Control.Change -= new EventHandler(this.ChangeEventHandler);
Casting
VB.NET
Dim obj As MyObject
Dim iObj As IMyObject
obj = Session("Some Value")
iObj = CType(obj, IMyObject)
C#
MyObject obj = (MyObject)Session["Some Value"];
IMyObject iObj = obj;
VB.NET
Dim i As Integer
Dim s As String
Dim d As Double
i = 3
s = i.ToString()
d = CDbl(s)
' See also CDbl(...), CStr(...), ...
C#
int i = 3;
String s = i.ToString();
double d = Double.Parse(s);
Using Objects
VB.NET
Dim hero As SuperHero = New SuperHero
' or
Dim hero As New SuperHero
With hero
.Name = "SpamMan"
.PowerLevel = 3
End With
hero.Defend("Laura Jones")
hero.Rest() ' Calling Shared method
' or
SuperHero.Rest()
Dim hero2 As SuperHero = hero ' Both reference the same object
hero2.Name = "WormWoman"
Response.Write(hero.Name) ' Prints WormWoman
hero = Nothing ' Free the object
If hero Is Nothing Then _
hero = New SuperHero
Dim obj As Object = New SuperHero
If TypeOf obj Is SuperHero Then _
Response.Write("Is a SuperHero object.")
' Mark object for quick disposal
Using reader As StreamReader = File.OpenText("test.txt")
Dim line As String = reader.ReadLine()
While Not line Is Nothing
Response.Write(line)
line = reader.ReadLine()
End While
End Using
C#
SuperHero hero = new SuperHero();
// No "With" construct
hero.Name = "SpamMan";
hero.PowerLevel = 3;
hero.Defend("Laura Jones");
SuperHero.Rest(); // Calling static method
SuperHero hero2 = hero; // Both reference the same object
hero2.Name = "WormWoman";
Response.Write (hero.Name); // Prints WormWoman
hero = null ; // Free the object
if (hero == null)
hero = new SuperHero();
Object obj = new SuperHero();
if (obj is SuperHero)
Response.Write ("Is a SuperHero object.");
// Mark object for quick disposal
using (StreamReader reader = File.OpenText("test.txt")) {
string line;
while ((line = reader.ReadLine()) != null)
Response.Write(line);
}
Class Definition with Inheritance
VB.NET
Imports System
Namespace MySpace
Public Class Foo : Inherits Bar
Dim x As Integer
Public Sub New()
MyBase.New()
x = 4
End Sub
Public Sub Add(x As Integer)
Me.x = Me.x + x
End Sub
Overrides Public Function GetNum() As Integer
Return x
End Function
End Class
End Namespace
' VB.NETc /out:libraryVB.NET.dll /t:library
' library.VB.NET
C#
using System;
namespace MySpace {
public class Foo : Bar {
int x;
public Foo() { x = 4; }
public void Add(int x) { this.x += x; }
override public int GetNum() { return x; }
}
}
// csc /out:librarycs.dll /t:library
// library.cs
Implementing an Interface
VB.NET
Public Class MyClass : Implements IEnumerable
...
Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
...
End Function
End Class
C#
public class MyClass : IEnumerable {
...
IEnumerator IEnumerable.GetEnumerator() {
...
}
}
Structs
VB.NET
Structure StudentRecord
Public name As String
Public gpa As Single
Public Sub New(ByVal name As String, ByVal gpa As Single)
Me.name = name
Me.gpa = gpa
End Sub
End Structure
Dim stu As StudentRecord = New StudentRecord("Bob", 3.5)
Dim stu2 As StudentRecord = stu
stu2.name = "Sue"
Response.Write(stu.name) ' Prints Bob
Response.Write (stu2.name) ' Prints Sue
C#
struct StudentRecord {
public string name;
public float gpa;
public StudentRecord(string name, float gpa) {
this.name = name;
this.gpa = gpa;
}
}
StudentRecord stu = new StudentRecord("Bob", 3.5f);
StudentRecord stu2 = stu;
stu2.name = "Sue";
Response.Write (stu.name); // Prints Bob
Response.Write (stu2.name); // Prints Sue
Constructors / Destructors
VB.NET
Class SuperHero
Private _powerLevel As Integer
Public Sub New()
_powerLevel = 0
End Sub
Public Sub New(ByVal powerLevel As Integer)
Me._powerLevel = powerLevel
End Sub
Protected Overrides Sub Finalize()
' Desctructor code to free unmanaged resources
MyBase.Finalize()
End Sub
End Class
C#
class SuperHero {
private int _powerLevel;
public SuperHero() {
_powerLevel = 0;
}
public SuperHero(int powerLevel) {
this._powerLevel= powerLevel;
}
~SuperHero() {
// Destructor code to free unmanaged resources.
// Implicitly creates a Finalize method
}
}
File I/O
VB.NET
Imports System.IO
' Write out to text file
Dim writer As StreamWriter = File.CreateText("c:\myfile.txt")
writer.WriteLine("Out to file.")
writer.Close()
' Read all lines from text file
Dim reader As StreamReader = File.OpenText("c:\myfile.txt")
Dim line As String = reader.ReadLine()
While Not line Is Nothing
Console.WriteLine(line)
line = reader.ReadLine()
End While
reader.Close()
' Write out to binary file
Dim str As String = "Text data"
Dim num As Integer = 123
Dim binWriter As New BinaryWriter(File.OpenWrite("c:\myfile.dat"))
binWriter.Write(str)
binWriter.Write(num)
binWriter.Close()
' Read from binary file
Dim binReader As New BinaryReader(File.OpenRead("c:\myfile.dat"))
str = binReader.ReadString()
num = binReader.ReadInt32()
binReader.Close()
C#
using System.IO;
// Write out to text file
StreamWriter writer = File.CreateText("c:\\myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();
// Read all lines from text file
StreamReader reader = File.OpenText("c:\\myfile.txt");
string line = reader.ReadLine();
while (line != null) {
Console.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();
// Write out to binary file
string str = "Text data";
int num = 123;
BinaryWriter binWriter = new BinaryWriter(File.OpenWrite("c:\\myfile.dat"));
binWriter.Write(str);
binWriter.Write(num);
binWriter.Close();
// Read from binary file
BinaryReader binReader = new BinaryReader(File.OpenRead("c:\\myfile.dat"));
str = binReader.ReadString();
num = binReader.ReadInt32();
binReader.Close();
1 Comments:
Great Article, Just a suggestion from me : Please display the article more spacious and more clear. Then it will be very easy to read and understand as well.
I haven't seen any articles on XML in your blog. Please try to cover that topic as well.
Post a Comment
<< Home