In this article I will explain with an example, how to reverse a String using C# and VB.Net.
This article will illustrate how to create a simple STATIC function which can be used in ASP.Net Web Forms, ASP.Net MVC, ASP.Net Core, Windows Applications and also Console Applications built in C# or VB.Net.
 
 
Function to Reverse a String in C# and VB.Net
The ReverseString function accepts a string i.e. input as parameter.
First, the input string is converted into an Array of Characters using the ToCharArray function.
Then using a reverse FOR LOOP, the items inside the Character Array are traversed and on by one each character is appended to another string i.e. output.
Thus by appending the character one by one in reverse order, a reverse string is generated.
Finally, the output string is returned.
C#
private static string ReverseString(string input)
{
    string output = string.Empty;
    char[] chars = input.ToCharArray();
    for (int i = chars.Length - 1; i >= 0; i--)
    {
        output += chars[i];
    }
 
    return output;
}
 

VB.Net
Private Shared Function ReverseString(ByVal input As String) As String
    Dim output As String = String.Empty
    Dim chars As Char() = input.ToCharArray()
 
    For i As Integer = chars.Length - 1 To 0 Step -1
        output &= chars(i)
    Next
 
    Return output
End Function
 
 
Reverse a String in ASP.Net with C# and VB.Net
Now, using the above ReverseString function we will learn how to reverse string in ASP.Net with C# and VB.Net.
HTML Markup
The HTML Markup consists of an ASP.Net TextBox, a Button and a Label. The Button has been assigned with an OnClick event handler which performs the process of reversing a string.
<asp:TextBox ID="txtName" runat="server" />
<asp:Button ID="btnReverse" Text="Reverse" runat="server" OnClick="Reverse" />
<hr />
<asp:Label id="lblReverseString" runat="server" />
 
Code
When the Reverse Button is clicked, the value of the TextBox is passed to the ReverseString function (explained above) and the returned reversed string is assigned to the Label control.
C#
protected void Reverse(object sender, EventArgs e)
{
    lblReverseString.Text = ReverseString(txtName.Text);
}
 

VB.Net
Protected Sub Reverse(ByVal sender As Object, ByVal e As EventArgs)
    lblReverseString.Text = ReverseString(txtName.Text)
End Sub
 
 
Screenshot
Reverse a String using C# and VB.Net
 
 
Demo
 
 
Downloads