Here are three Extension Methods which let you use the Left, Mid and Right Methods from VB6 in C# and VB.NET. The Extension Methods simply wrap the on-board .NET Framework Method Substring. These Extension Methods are now part of the Fesslersoft.Extensions.
Samples
C# Sample
#region using System; #endregion namespace de.Fesslersoft.Extensions { public static class Extensions { public static String Left(this string input, int length) { var result = ""; if ((input.Length <= 0)) return result; if ((length > input.Length)) { length = input.Length; } result = input.Substring(0, length); return result; } public static String Mid(this string input, int start, int length) { var result = ""; if (((input.Length <= 0) || (start >= input.Length))) return result; if ((start + length > input.Length)) { length = (input.Length - start); } result = input.Substring(start, length); return result; } public static String Right(this string input, int length) { var result = ""; if ((input.Length <= 0)) return result; if ((length > input.Length)) { length = input.Length; } result = input.Substring((input.Length - length), length); return result; } } }
VB.NET Sample
Imports System Namespace de.Fesslersoft.Extensions Public Friend Module Extensions <System.Runtime.CompilerServices.Extension> _ Public Function Left(input As String, length As Integer) As [String] Dim result = "" If (input.Length <= 0) Then Return result End If If (length > input.Length) Then length = input.Length End If result = input.Substring(0, length) Return result End Function <System.Runtime.CompilerServices.Extension> _ Public Function Mid(input As String, start As Integer, length As Integer) As [String] Dim result = "" If ((input.Length <= 0) OrElse (start >= input.Length)) Then Return result End If If (start + length > input.Length) Then length = (input.Length - start) End If result = input.Substring(start, length) Return result End Function <Runtime.CompilerServices.Extension> _ Public Function Right(input As String, length As Integer) As [String] Dim result = "" If (input.Length <= 0) Then Return result End If If (length > input.Length) Then length = input.Length End If result = input.Substring((input.Length - length), length) Return result End Function End Module End Namespace
If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.
Related links:
- Visual Basic 6 String Functions
- String.Substring Method
- Extension Methods (C# Programming Guide)
- Fesslersoft-Extensions (GITHUB)
- FesslerSoft.Extensions (NUGET)
RT @CodeSnippetsNET: Left Mid Right functions for CSharp http://t.co/Hhe9Vf2HHk #vb #csharp #dotnet #programming