Very often when migrating traditional windows application written in VB6, we may come across the inbuilt functions which were available in VB6, but not available in C#. One such function is Mid Function.

Visual Basic has a Mid function and a Mid statement. These elements both operate on a specified number of characters in a string, but the Mid function returns the characters while the Mid statement replaces the characters.

Mid Function has following parameters

Mid Statement

Replaces a specified number of characters in a String variable with characters from another string.
Mid Statement has the following parameters.

StringExpression

Required. String expression that replaces part of Target.

Here is the C# version for the same code.

  1. /// <param name="newChar"> Character to be replaced.</param>
  2. /// <returns></returns>
  3. public static string Mid(string input, int index, char newChar)
  4. {
  5. if (input == null)
  6. {
  7. throw new ArgumentNullException("input");
  8. }
  9. char[] chars = input.ToCharArray();
  10. chars[index-1] = newChar;
  11. return new string(chars);
  12. }
  13. /// <summary>
  14. /// This is equivalent to Mid Function in VB6
  15. /// </summary>
  16. /// <param name="s"> String to Check.</param>
  17. /// <param name="a">Position of Character</param>
  18. /// <param name="b">Length </param>
  19. /// <returns></returns>
  20. public static string Mid(string s, int a, int b)
  21. {
  22. string temp = s.Substring(a - 1, b);
  23. return temp;
  24. }
  25. }