简体   繁体   中英

Error when declaring a String by assigning a value from a method in c#

I am learning C# in Unity but I am receiving a weird error. Error is saying "Expression denotes a variable', where a method group' was expected"

This is the line that gives the error:

string walkingDir = walkingDir();

This is the walkingDir() method:

private string walkingDir(){
return "str";}

Replacing

string walkingDir = walkingDir(); 

with

string walkingDir = "str";

works.

Your problem is that your variable and method have the same name. Change the name of your variable and it will compile. Eg

string walkDir = walkingDir(); 

You are getting that error because the name of the function is the-same as the name of the variable which are both "walkingDir" .

You have to either rename the function or the variable.

string walkingDir = getWalkingDir();

and

private string getWalkingDir()
{
    return "str";
}

Another way to fix this without re-naming the variables is to use the this keyword to tell the compiler to use the local function name instead of the variable name.

This should work too:

string walkingDir = this.walkingDir();

and

private string walkingDir()
{
    return "str";
}

Even though that should work, I encourage you to prevent naming your variable or function name the-same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM