Reputation: 2859
I'm still not practiced in oop.. now I know the importantness of it :)
I have many methods and now I like to save collected strings in public variables to have the possiblity to access them from another function.
normaly I would make just public or private variables with get and set.
But this I think it's not so clean because this propertys are in "every intellisense" visible.
I think to do this into a class may be "testClass" and define the properties there.
But now, how I access to the values which I have written into the propertys of this class? To write them in I have to create a new instance of the class, but how access to the created instance?
// edit
protected void GetValues()
{
// Access to the public variable town.
string myNewtown = publictown;
string myNewName = publicname;
// How to acces to the values which I saved in the class informations?
// I like anything like that
string myNewtown = informations.publictown;
string myNewName = informations.publicname;
// or
string myNewtown = myinfo.publictown;
string myNewName = myinfo.publicname;
}
protected void Setvalues()
{
informations myinfo = new informations()
{
publicname = "leo",
publictown = "london"
};
}
private string publicname { get; set; }
private string publictown { get; set; }
private class informations
{
public string publicname { get; set; }
public string publictown { get; set; }
}
Thanks
Upvotes: 0
Views: 76
Reputation: 7879
If you want access a created object, you need to store reference to it after creating.
Having look at your sample, I can offer you following change:
protected void GetValues()
{
// Access to the public variable town.
string myNewtown = publictown;
string myNewName = publicname;
// or
string myNewtown = myinfo.publictown;
string myNewName = myinfo.publicname;
}
protected void Setvalues()
{
publicname = "leo";
publictown = "london";
}
// we store reference to internal object
informations myinfo = new informations();
// and delegate property access to its properties.
public string publicname
{
get{ return informations.publicname;}
set{ informations.publicname = value; }
}
public string publictown
{
get{ return informations.publictown;}
set{ informations.publictown = value; }
}
private class informations
{
public string publicname { get; set; }
public string publictown { get; set; }
}
Upvotes: 1
Reputation: 172310
If you want your properties to be accessible without creating an instance, use the static
keyword.
EDIT: In your example, you would replace
public string publicname { get; set; }
with
public static string publicname { get; set; }
which allows you to read the field as
string myNewname = informations.publicname;
and set it with
informations.publicname = "whatever";
Of course, this means that you can only have one instance of publicname in your application -- in particular, in an ASP.NET application, this might not be what you want!
Upvotes: 1