mathinvalidnik
mathinvalidnik

Reputation: 1600

How to add extension method to String in c#

if I had the string : string a = "Hello there"

I wish I could do : a.ReplaceThereSubstring()

and to expect a = "Hello here"

I tried like this:

public static class ChangeString
    {
        public static string ReplaceThereSubstring(this String myString)
        {
           return myString.Replace("there","here");
        }
    }

but it always returns null.

Upvotes: 0

Views: 159

Answers (3)

Alberto
Alberto

Reputation: 15941

You cannot modify an existing string because strings are immutable.

So an expression like myString.Replace("there", "here"); will not alter the myString instance.

Your extension method is actually correct but you should use it in this way:

a = a.ReplaceThereSubstring();

Upvotes: 2

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

in that case you should do this to run your code:

string a = "Hello there"
a = a.ReplaceThereSubstring();

You can not replace string's value in extension method because strings are immutable

Upvotes: 2

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

You need to assign the result, of course:

string b = a.ReplaceThereSubString();

Upvotes: 1

Related Questions