We now look at some of the ways in which C# and Visual Basic.NET are different from Java.
Here is an example of a struct type coded in C#:
namespace First
{
public struct SPoint
{
private int iX;
private int iY;
public SPoint(int pX, int pY)
{
iX = pX;
iY = pY;
}
public override string ToString()
{
return iX + ":" + iY;
}
}
}
Here is a method that uses this struct type:
using System;
namespace First
{
public class SPointTest
{
public static void Main()
{
SPoint tSPoint = new SPoint(100, 200);
Console.WriteLine(tSPoint);
SPoint tAnotherSPoint = tSPoint;
Console.WriteLine(tAnotherSPoint);
}
}
}
enum Days : int
{
Sunday = 1,
Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday
}
ArrayList tArrayList = new ArrayList();
i = 27; tArrayList.Add(i);an object is automatically created.
Point tPoint = new Point(100, 200); tArrayList.Add(tPoint);
If instead we use a struct type, boxing takes place:
SPoint tSPoint = new SPoint(300, 400); tArrayList.Add(tSPoint);
int i = 27; Integer tInteger = new Integer(i); tArrayList.Add(tInteger);
This means the value of the object is copied into the variable:
int j = (int) tArrayList[0]; Point tGotPoint = (Point) tArrayList[1]; SPoint tGotSPoint = (SPoint) tArrayList[2];
The following kinds of parameters are available:
| Java | C# | VB.NET |
| value | value | ByVal |
| ref | ByRef | |
| out | ||
| params |
private static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
...
i = 42;
j = 27;
Swap(ref i, ref j);
// i has the value 27
// j has the value 42
switch (tCommand)
{
case "add":
...
case "remove":
...
}
tOp = -1;
switch (tCommand)
{
case "add":
tOp = 1;
goto case "remove";
case "remove":
...
}
public class Point
{
private int iX;
private int iY;
public Point(int pX, int pY)
{
iX = pX; iY = pY;
}
public int X
{
get { return iX; }
set { iX = value; }
}
...
}
...
Point tPoint = new Point(100, 200);
int tX = tPoint.X; // uses get
tPoint.X = 150; // uses set
tPoint.X++; // uses get and set
delegate int Analyse(string s);
private static int StringLength(string pString)
{
return pString.Length;
}
Analyse tAnalyse = new Analyse(StringLength);The variable tAnalyse now contains a pointer to the StringLength method.
private static void iProcess(Analyse pAnalyse)
{
string tString = Console.ReadLine();
int tInt = pAnalyse(tString);
Console.WriteLine(tInt);
}
int tInt = pAnalyse(tString);
iProcess(tAnalyse);
delegate void EventHandler(object sender, EventArgs e);
public event EventHandler Click;
private Button iAddButton = new Button();
iAddButton.Click += new EventHandler(iHandleClick);
protected void iHandleClick(object sender, EventArgs e)
{
...
}
FileStream tFileStream = File.Open("data", FileMode.Open);
This can cause the FileNotFoundException exception.
private void iProcessFile() throws FileNotFoundException
{
...
}