I'm a real newbie programmer and I'm trying to make an overload that will share a variable. Basically what I want to do is have a method with one overload that writes an integer value to a variable within it and another overload that simply returns that value.
Now I tried to do it like this:
private int GetQID(int qID)
{
int ID = qID;
}
private int GetQID()
{
return ID;
}
This unfortunately, doesn't work because the second overload can't access the "ID" variable of the first overload. Is there any way without resorting to global variables, that I can do this?
No, local variables are purely local to the method in question. It's not really clear what you're trying to achieve, but if you want any state which persists between method calls, you'll need a field, and probably expose it as a property.
private int id;
public int Id
{
set
{
// Perform some validation?
id = value;
}
get { return id; }
}
If you just want a property which is backed by a field with no other logic, then automatically implemented properties are useful:
public int Id { get; set; }
See more on this question at Stackoverflow