Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Uri.IsHexEncoding() Method in C#
The Uri.IsHexEncoding() method in C# determines whether a character at a specific position in a string is hexadecimal encoded. This method is useful when working with URIs that contain percent-encoded characters, where hexadecimal encoding follows the pattern %XX (a percent sign followed by two hexadecimal digits).
Syntax
Following is the syntax −
public static bool IsHexEncoding(string pattern, int index);
Parameters
-
pattern − The string to check for hexadecimal encoding.
-
index − The zero-based position in the pattern where the check should begin.
Return Value
Returns true if the character at the specified index is hexadecimal encoded (follows the %XX pattern), otherwise returns false.
Using IsHexEncoding() at Valid Position
This example checks for hexadecimal encoding at index 0, where the pattern starts with % −
using System;
public class Demo {
public static void Main() {
string pattern = "%50";
bool res = Uri.IsHexEncoding(pattern, 0);
if (res)
Console.WriteLine("Valid: Hexadecimal Encoded");
else
Console.WriteLine("Invalid: Hexadecimal Encoded");
}
}
The output of the above code is −
Valid: Hexadecimal Encoded
Using IsHexEncoding() at Invalid Position
This example checks for hexadecimal encoding at index 1, which does not start with the % character −
using System;
public class Demo {
public static void Main() {
string pattern = "%60";
bool res = Uri.IsHexEncoding(pattern, 1);
if (res)
Console.WriteLine("Valid: Hexadecimal Encoded");
else
Console.WriteLine("Invalid: Hexadecimal Encoded");
}
}
The output of the above code is −
Invalid: Hexadecimal Encoded
Comprehensive Example with Multiple Test Cases
This example demonstrates various scenarios to understand the method behavior better −
using System;
public class Demo {
public static void Main() {
string[] patterns = { "%20", "%5A", "%G5", "Hello%20World", "ABC" };
int[] indices = { 0, 0, 0, 5, 0 };
for (int i = 0; i < patterns.Length; i++) {
bool result = Uri.IsHexEncoding(patterns[i], indices[i]);
Console.WriteLine($"Pattern: '{patterns[i]}', Index: {indices[i]}, Result: {result}");
}
}
}
The output of the above code is −
Pattern: '%20', Index: 0, Result: True Pattern: '%5A', Index: 0, Result: True Pattern: '%G5', Index: 0, Result: False Pattern: 'Hello%20World', Index: 5, Result: True Pattern: 'ABC', Index: 0, Result: False
Conclusion
The Uri.IsHexEncoding() method is a utility function that validates whether a specific position in a string contains a valid hexadecimal encoding pattern (%XX). It returns true only when the character at the specified index is % followed by exactly two valid hexadecimal digits.
