1

I am currently working on a program and need to use the .Replace() method to remove a certain substring from a string. However, the code just doesn't seem to be working.

Below is the code I am using:

if (filter.Contains("AND [Type]"))
        {
            String test = "AND [Type] = '" + type + "'";
            filter.Replace(test, "");
        }
        else if (filter.Contains("Type") == true)
        {
            String test = "[Type] = '" + type + "'";
            filter.Replace(test, "");
        }

I have debugged the code and when stepping through it String test is set to exactly what is contained within the filter - however the code just runs through attempts the replace method but leaves the filter unchanged.

Is there any other way I can attempt to get this working or do I need to take a few steps back and come up with another idea for getting this working?

1
  • strings in C# are immutable. Commented Nov 6, 2017 at 9:02

3 Answers 3

3

You must assign the value to given string:

filter = filter.Replace(test, "");

Replace() returns a new string, more here

Sign up to request clarification or add additional context in comments.

Comments

1

You need to set the replace to a variable so filter = filter.Replace(test, "");

Its a common issue with some of the functions like date adding hours, string replace..

2 Comments

I knew this as well as I've used the method in another part of my code! I debugged for agers and didn't notice the simple error - Thanks!
@benjiiiii as I said, its a common mistake .. its easy to miss for that reason
0

Look at he function definition string.Replace returns your new string:

https://msdn.microsoft.com/de-de/library/fk49wtc1(v=vs.110).aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.