BlackStarHH BlackStarHH - 17 days ago 7
C# Question

Useclasses without making new instances

I want to take a string in my mainpage and put it inside my class so I can get it in the next window. My Class is simple and looks like this:

name: Spreadsheet

private string itemType;

public string ItemType
{
get { return itemType; }
set { itemType = value; }
}


I can change it just fine if I make a new instance, but that will remove everything inside it - I don't want that. I Call the class using this line:

private Spreadsheet ss = new Spreadsheet();


When I call this method I make a new instance
new Spreadsheet()
which incorrectly puts all the strings into null. How can I avoid this?

Answer

Like Tyler Day said

I think you might be looking for the static keyword. – Tyler Day

That fixed my problems making the private string itemType into private static string itemType was what I missed out :)

To explain why is that static fields are class-level variables that are per-type rather than per-instance