简体   繁体   中英

c# Equivalent to VB6 Public variable

Suppose I my project contains a Form and a Class. I would like to create a variable that can be accessed by both the Form and the class. In VB6 I could create a public variable in the (module / class), and easily access it like so:

VB6 Example

[Module code]

Public string_name as string

[/Module code]

[Form Code]

string_name = "test data"
MsgBox(string_name) ' Returns "test data"

[/Form Code]

How could I produce the above functionality with C#? I'm assuming I'd have to create a public class, but I'm not sure of the best way to declare public variables.

thank you,

Evan

You can create a public static class with a public static variable.

public static class MyPublicData
{

    public static string MyData1 = "My public data";

}

To use:

var x = MyPublicData.MyData1;

You can do the same in c# (expose a field as public), though that is not good practice.

Use properties instead:

// public string property
public string string_name { get; set; }

// within class    
string_name = "test data";
MsgBox(string_name); 

// from another class
myClassInstance.string_name = "other test data";
public class MyClass
{
  public int MyPublicVariable;
  public int MyPublicProperty {get; set; }
}

Try a public class with a public static variable. Example:

public class PortalResources
    {
        #region Members

        public enum Mode 
        {
            LargeIconMode,
            SmallIconMode, 
            DetailsMode
        };

        public static int LargeIconSize = 150;
        public static int SmallIconSize = 75;
        public static string Name = "Name";

        #endregion

    }

Usage:

int IconSize = PortalResources.LargeIconSize;
int ViewMode = PortalResources.Mode.LargeIconMode;

The equivalent of a VB public (or global) variable is a public static property on a class.

You have to specify

Classname.PropertyName

To access it, though.

If you need the value to be a constant or static readonly value then place it in a static class:

public class Globals
{
    public const String value = "Hello World";
}

public static class Globals
{
    public static value2 = "Hello World";
}

If the value just needs to be accessible (not readonly), then you're better off sticking this value in a settings file and grabbing the setting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM