C# VB.Net String Comparison with or without Case Sensitivity in Asp.Net

When we need to compare string values we need to decide first whether we will consider case comparison or not. Asp.Net provides us System.StringComparison.Ordinal to compare string values. Using System.StringComparison.Ordinal we can compare strings in both way like with case sensitivity or without case sensitivity. It is important to use the correct kind of comparison for the specific task. A basic ordinal comparison is case sensitive, means the two strings must match character by character. By using System.StringComparison.Ordinal, you can also compare strings in respect to the culture. Please note that Ordinal is the fastest way to compare two strings.

Sample Output:
string comparison csharp Vb.Net

C# Code to compare two String:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string strFirst = "Welcome";
            string strSecond = "WELCOME";

            // Compare string with case Sensitivity
            Response.Write(string.Format("Ordinal comparison with Case Sensitivity: {0} and {1} are {2}", strFirst, strSecond, strFirst.Equals(strSecond, StringComparison.Ordinal) ? "equal." : "not equal."));

            // Compare string without case Sensitivity
            Response.Write(string.Format("<br/>Ordinal comparison without Case Sensitivity: {0} and {1} are {2}", strFirst, strSecond, strFirst.Equals(strSecond, StringComparison.OrdinalIgnoreCase) ? "equal." : "not equal."));
        }
    }

VB.Net Code to compare two String:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim strFirst As String = "Welcome"
            Dim strSecond As String = "WELCOME"

            ' Compare string with case Sensitivity
            Response.Write(String.Format("Ordinal comparison with Case Sensitivity: {0} and {1} are {2}", strFirst, strSecond, If(strFirst.Equals(strSecond, StringComparison.Ordinal), "equal.", "not equal.")))

            ' Compare string without case Sensitivity
            Response.Write(String.Format("<br/>Ordinal comparison without Case Sensitivity: {0} and {1} are {2}", strFirst, strSecond, If(strFirst.Equals(strSecond, StringComparison.OrdinalIgnoreCase), "equal.", "not equal.")))
        End If

    End Sub

Hope now you can compare strings in C# VB.Net.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*