Reputation: 1611
I am trying to make a class so when I do the following inside a file:
Functions LoginFunctions = new Functions();
LoginFunctions.loadFunctions();
It will create my object which I need, and make it public so every form which calls the class will be able to use it. The class file is below.
namespace App
{
public class Functions
{
public void loadFunctions()
{
TaskbarItemInfo taskbarItemInfo = new TaskbarItemInfo();
}
}
}
It doesn't seem to be making the taskbarItemInfo object public, and it is not letting me use it anywhere else other then inside the class. How do I make it public so every file that calls the class can use the object?
Upvotes: 2
Views: 2701
Reputation: 22064
You need to make the variable public.
namespace App
{
public class Functions
{
public TaskbarItemInfo TaskbarItemInfo { get; private set; }
public void loadFunctions()
{
TaskbarItemInfo = new TaskbarItemInfo();
}
}
}
EDIT: You could also do the initialization of the items in the constructor.
namespace App
{
public class Functions
{
public TaskbarItemInfo TaskbarItemInfo { get; private set; }
public Functions()
{
loadFunctions();
}
private void loadFunctions()
{
TaskbarItemInfo = new TaskbarItemInfo();
}
}
}
Then you don't need the LoginFunctions.loadFunctions();
line of code after you initialize your LoginFunctions object.
Upvotes: 2
Reputation: 20769
Your taskbaritem class is in the scope of the method and therefore you wont be able to access it outsite of the class.
Create a public property or return it in the method.
namespace App
{
public class Functions
{
private TaskbarItemInfo _taskbarItemInfo;
public TaskbarItemInfo taskbarItemInfo
{
get
{
return _taskbarItemInfo;
}
}
public void loadFunctions()
{
_taskbarItemInfo = new TaskbarItemInfo();
}
}
}
I would also go and change the loadFunctions method to a constructor which creates all the objects you need.
public Functions()
{
_taskbarItemInfo = new TaskbarItemInfo();
}
Upvotes: 4
Reputation: 3387
You probably want to access it as a property which generates a private static member when needed.
namespace App
{
public class Functions
{
private static TaskbarItemInfo _taskbarItemInfo;
public static TaskbarItemInfo TaskBarItemInfoProperty
{
get{
if (_taskbarItemInfo == null)
{
_taskbarItemInfo = new TaskbarItemInfo();
}
return _taskbarItemInfo;
}
}
}
public class Test
{
public void testFunction()
{
Functions.TaskBarItemInfoProperty.doSomething();
}
}
}
Upvotes: 1
Reputation: 9099
As the others have mentioned, make it a property, for example like so:
public class Functions
{
public TaskbarItemInfo TaskbarItemInfo { get; private set; }
public void loadFunctions()
{
this.TaskbarItemInfo = new TaskbarItemInfo();
}
}
Upvotes: 5
Reputation: 4277
In the example you provide, taskbarItemInfo
is declared within the local scope of the loadFunctions()
method. If you want it to be public for some class, you must make it a class member before you can make it public.
Upvotes: 2