Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ref parameters not changing value? c#

I'm currently writing a simple program for college work, and using a function to detect characters in a string and remove them, the function is supposed to output a bool and the new string is supposed in a reference parameter however the reference parameter isn't working and data isn't being carried over?

    public static bool DetectAndRemoveCharacter(ref string Word, char Character)
    {
        bool returnVal = false;
        for (int x = 0; x < Word.Length; x++)
        {
            if (Word[x] == Character)
            {
                Word.Remove(x, 1);
                returnVal = true;
                break;
            }
        }
        return returnVal;
    }

The bool is returned but (Letters) is not being altered, It could be something simple, but I didn't think refs would to be too complicated to use, I could try and fix it with return object lists, but it would be much simpler if I could accomplish it this way.

Set = DetectAndRemoveCharacter(ref Letters, '?');
like image 515
Sebastian Southwell Avatar asked Sep 09 '26 01:09

Sebastian Southwell


1 Answers

Strings are immutable objects and cannot be changed. The method Remove does not chcange the original object, you have to reassign the result to the variable:

Word = Word.Remove(x, 1);
like image 75
Flat Eric Avatar answered Sep 10 '26 15:09

Flat Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!