Method Scope

J

Joseph

I am trying to use a string variable (strX) inside a method. The method looks
like the following:

Class Something
{
public string strX;

public static DataSet ReturnDataSet(string strSql)
{
//This method returns a Dataset
strX
}
}
For some reason unknown to me, strX loses scope inside this method. Can
someone please explain why and is there a way around this? Thanks
 
A

Alberto Poblacion

Joseph said:
I am trying to use a string variable (strX) inside a method. The method
looks
like the following:

Class Something
{
public string strX;

public static DataSet ReturnDataSet(string strSql)
{
//This method returns a Dataset
strX
}
}
For some reason unknown to me, strX loses scope inside this method. Can
someone please explain why and is there a way around this? Thanks

The reason is that the method is static while the variable is not.
Depending on what you are trying to achive, the solution is to either
mark the variable as static (public static string strX), or make the method
an instance method (remove the "static" keyword).
 
J

Jon Skeet [C# MVP]

Joseph said:
I am trying to use a string variable (strX) inside a method. The method looks
like the following:

Class Something
{
public string strX;

public static DataSet ReturnDataSet(string strSql)
{
//This method returns a Dataset
strX
}
}
For some reason unknown to me, strX loses scope inside this method. Can
someone please explain why and is there a way around this? Thanks

The method is static - in other words, it's not related to any
particular instance of Something.

The variable is an instance variable, which means each Something can
have a different value. That means it doesn't make sense to refer to it
from a static method, without a particular instance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top