I was writing a console application, I wrote a common method to reuse it like this.
"Keyword 'this' is not valid in a static property, static method, or static field initializer"
I googled and found the reason from MSDN, which says static methods are independent of any instance of the containing class - Reference
The work around i did was to create a class and place this method inside. Create a object of the class and call this method.
Hope it helps...
Regards
Fauzi
2 comments:
Hello, Mohammed!
Have a nice day, my friend.
I faced the same issue, please check my code below
using System;
class TestScope
{
int x = 10;
static int y = 20;
static void Main()
{
int x = 100;
int y = 200;
Console.WriteLine(x); // local value of x
Console.WriteLine(y); // local value of y
Console.WriteLine(this.x); // instance x (This line is throwing 'this' erro)
Console.WriteLine(TestScope.y); // static y
}
}
can you suggest an alternative with example?
Post a Comment