So I have a function:
List names = new string();
private static void getName(string name)
{
names.add(name);
}
When I at
You cant access it this way, you need to instanciate the class containing a member.
You need to tell the system which list of names you're interested in. It's part of the state of an object, an instance of the class... but which one? Maybe you've created several instances of the class - maybe you've created no instances of the class. The static method has no visibility of that - so which instance do you want it to fetch the names
variable value from?
To put it in another example, suppose we had a class like this:
public class Person
{
public double MassInGrams { get; set; }
public double HeightInMetres { get; set; }
public static double ComputeBodyMassIndex()
{
// Which person are we interested in?
}
}
Person p1 = new Person { MassInGrams = 76203, HeightInMetres = 1.8 };
Person p2 = new Person { MassInGrams = 65000, HeightInMetres = 1.7 };
double bmi = Person.ComputeBodyMassIndex();
What would you expect the result to be? You've asked the Person
class to compute "the BMI" but without telling it whose BMI to compute. You need to give it that information.
Some options for your situation:
names
to be static insteadBy the way, that's a very strange method name for something which adds a name. It's also somewhat unconventional...
names
is an object that will exist in the instances of the class e.g. MyClass mc = new MyClass();
then you can access mc.names
. A static field can be called without an instance of the class just with the classname, e.g. MyClass.getName("");
will work. So when you think logically, the class doesn't contain names, only 'the instances of that class' contain it. Therefore, you either make that list static too and it will be 'the same List instance' everywhere when you call MyClass.names
or make the getName method non-static, and it will be only called from instances, therefore no MyClass.getName("")
will be possible, but mc.getName("");
It's a matter of what you are exactly trying to do.
Static methods can not access class fields. Either make names static, or make getName() non-static. What do you mean by "Compatible". Ask yourself... does the method need to be static? What is its purpose and how do you intend to use it?
You need to make names
static if you want to use it from inside of a static method:
// If this is static, you can use it from your static method
static List<string> names = new List<string>();
The issue is that getName
is defined on your type, not on an instance of the type. However, names
is defined so each instance of your type gets its own value.