Saturday, October 27, 2007

Functions of VB.NET & C# language

Functions


In vb.net & c# language Functions are differ.Code Functions of vb.net & c# language.

____________________________________________________________________

VB.NET

Pass by value (in, default), reference (in/out), and reference (out)
Sub TestFunc(ByVal x As Integer, ByRef y As Integer, ByRef z As Integer)
x += 1
y += 1
z = 5
End Sub

Dim a = 1, b = 1, c As Integer ' c set to zero by default
TestFunc(a, b, c)
Console.WriteLine("{0} {1} {2}", a, b, c) ' 1 2 5

' Accept variable number of arguments
Function Sum(ByVal ParamArray nums As Integer()) As Integer
Sum = 0
For Each i As Integer In nums
Sum += i
Next
End Function ' Or use Return statement like C#

Dim total As Integer = Sum(4, 3, 2, 1) ' returns 10

' Optional parameters must be listed last and must have a default value
Sub SayHello(ByVal name As String, Optional ByVal prefix As String = "")
Console.WriteLine("Greetings, " & prefix & " " & name)
End Sub

SayHello("Strangelove", "Dr.")
SayHello("Madonna")

-------------------------------------------------------------------------------------------------

C#

// Pass by value (in, default), reference (in/out), and reference (out)
void TestFunc(int x, ref int y, out int z) {
x++;
y++;
z = 5;
}

int a = 1, b = 1, c; // c doesn't need initializing
TestFunc(a, ref b, out c);
Console.WriteLine("{0} {1} {2}", a, b, c); // 1 2 5

// Accept variable number of arguments
int Sum(params int[] nums) {
int sum = 0;
foreach (int i in nums)
sum += i;
return sum;
}

int total = Sum(4, 3, 2, 1); // returns 10

/* C# doesn't support optional arguments/parameters. Just create two different versions of the same function. */
void SayHello(string name, string prefix) {
Console.WriteLine("Greetings, " + prefix + " " + name);
}

void SayHello(string name) {
SayHello(name, "");
}


-------------------------------------------------------------------------------------------------

Note: This code applicable for both desktop and web application.

-------------------------------------------------------------------------------------------------

No comments: