Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member '<method>' cannot be accessed with an instance reference

Tags:

c#

instance

The whole error text is:

Member 'System.Text.RegularExpressions.Regex.Replace(string, string, string, System.Text.RegularExpressions.RegexOptions)' cannot be accessed with an instance reference; qualify it with a type name instead

Here's the code. I removed "static" like in another post here, but it's still giving me the error.

I'd appreciate the assistance of all the experts on here - thanks!.

public string cleanText(string DirtyString, string Mappath)
{
    ArrayList BadWordList = new ArrayList();
    BadWordList = BadWordBuilder(BadWordList, Mappath);

    Regex r = default(Regex);
    string element = null;
    string output = null;

    foreach (string element_loopVariable in BadWordList)
    {
        element = element_loopVariable;
        //r = New Regex("\b" & element)
        DirtyString = r.Replace(DirtyString, "\\b" + element, "*****", RegexOptions.IgnoreCase);
    }

    return DirtyString;
}
like image 517
David Avatar asked Mar 05 '26 01:03

David


2 Answers

The problem is with the use of the method Replace not with the use of static in your declaration. You need to use the typename Regex instead of the variable r

DirtyString = Regex.Replace(DirtyString, "\\b" + element, "*****", RegexOptions.IgnoreCase);

The reason why is in C# you cannot access static methods through an instance of the type. Here Replace is static hence it must be used through the type Regex

like image 140
JaredPar Avatar answered Mar 07 '26 15:03

JaredPar


Ok, so first; default(Regex) will simply return null as Regex is a reference type. So even if your code compiled, it would certainly crash with a NullReferenceException at this line as you never assign anything valid to r.

DirtyString = r.Replace(DirtyString, "\\b" + element, "*****", RegexOptions.IgnoreCase);

Next, the compiler is telling you exactly what the problem is; Replace is a static method, not an instance method, so you need to use the typename as opposed to an instance variable.

DirtyString = Regex.Replace(...);
like image 30
Ed S. Avatar answered Mar 07 '26 14:03

Ed S.



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!