Home > Blockchain >  C# How to change a method from a void to string in order to implement an interface
C# How to change a method from a void to string in order to implement an interface

Time:10-05

I am new to C# and was attempting to do a quick sort. So the following method works if I changed "public string Sort(string input)" into "public void Sort(string input)." However, I have to use the former in order to implement an interface. I tried the following:

  1. Just use void method however it will not implement the interface which is needed
  2. Return null? However it breaks the console system.
  3. Create a separate method for the public string with a return value and pass it into the method with void string however it doesn't work.
public string Sort(string input)
        {
            string inputLower = input.ToLower();
            char[] charArr = inputLower.ToCharArray();

            quickSortMerge(charArr, 0, charArr.Length - 1);

            for (int i = 0; i < charArr.Length; i  )
            {
                Console.Write(charArr[i]);
            }

Is this doable?

CodePudding user response:

You could always return "", or a bit prettier String.Empty(same as the prior value), if you don't care about the result, if you're defining the interface and never use the returned value, you could simply have it return void though.

Looks like it should return the actual sorted string though, so instead of writing the string to a console, you can return the charArr as a string instead, which should be the sorted result, no?

Something like this:

public string Sort(string input)
{
    string inputLower = input.ToLower();
    char[] charArr = inputLower.ToCharArray();

    quickSortMerge(charArr, 0, charArr.Length - 1);

    return new string(charrArr);
  • Related