Reputation: 169
I have a class where there's a public static variable that I want to access from another class. Here's the class : In GlobalVariable.cs
public class GlobalVariable
{
public static int MoisVS = 3;
}
And I want to access to "MoisVS" from another class. Here's the class : In ArretPage.cs
var globalvariable = new ProjetTN.Class.GlobalVariable();
globalvariable.MoisVS; //<--- Make something like that.
I know it's possible in a WinForm app but is that possible in a Xamarin.forms app ?
Upvotes: 1
Views: 1482
Reputation: 14292
I will break this into steps.
1) File -> New File -> General -> Choose Empty Class -> Name it (e.g.UICONTROL_NAMES)
2) Add the following: (Sample code)
using System;
namespace iOSControls.HelperClass
{
public static class UICONTROL_NAMES
{
public const string textField = "Text Fields";
public const string inputTextField = "Input types - TextFields";
public const string button = "Buttons";
public const string label = "Label";
}
Have a note:
UICONTROL_NAMES class is inside a folder group called HelperClass and iOSControls is the project name.
3) On your ViewController.cs, add namespace directive.
using iOSControls.HelperClass;
using Foundation;
4) Access const strings in UICONTROL NAMES:
string controlName = UICONTROL_NAMES.textField;
Upvotes: 0
Reputation: 3283
You defined your MoisVS
as static so you can't access it from an instance variable. Accessing static members of a class you're using the class name itself. So for example accessing your MoisVS
will look like:
GlobalVariable.MoisVS
If you want to accesss it as an instance property you have to change your class to:
public class GlobalVariable
{
public int MoisVS = 3;
}
If there are only static or const values in your class. You can also decide to make your whole class static
public static class GlobalVariable
{
public static int MoisVS = 3;
public const string MyString = "";
}
this will prevent you from using the new keyword to create an instance of that class.
Upvotes: 1