How can I access a variable in one public class from another public class in C#?
I have:
public class Variables
{
static string name = "";
}
I need to call it from:
public class Main
{
}
I am working in a Console App.
That would just be:
Console.WriteLine(Variables.name);
and it needs to be public also:
public class Variables
{
public static string name = "";
}
I would suggest to use a variable instead of a public field:
public class Variables
{
private static string name = "";
public static string Name
{
get { return name; }
set { name = value; }
}
}
From another class, you call your variable like this:
public class Main
{
public void DoSomething()
{
string var = Variables.Name;
}
}
You need to specify an access modifier for your variable. In this case you want it public.
public class Variables
{
public static string name = "";
}
After this you can use the variable like this.
Variables.name
class Program
{
Variable va = new Variable();
static void Main(string[] args)
{
va.name = "Stackoverflow";
}
}
Related
I have this class that contains a static list
public class TypeList
{
public string Name;
public string NameTag;
public TypeList(string Name, string NameTag)
{
this.Name = Name;
this.NameTag = NameTag;
}
public static List<TypeList> DataType = new List<TypeList>() {
new TypeList("DataType","-1"),
new TypeList("OpOne","1"),
new TypeList("OpTwo","2"),
};
}
I then put the static list called DataType into a combobox:
public void RefreshList()
{
List<TypeList> data = new List<TypeList>();
data = TypeList.DataType;
typeCB.DataSource = data;
typeCB.DisplayMember = "Name";
typeCB.ValueMember = "NameTag";
typeCB.SelectedValue = -1;
typeCB.SelectedText = "Select DataType";
}
However, when I run it, all I get are the classnames in my combobox. Is something wrong with my code? I tried to do
data.Select(x=>x.Name).ToList()
But that just gives me the name portion.
I might be wrong, but based on the Documentation and Example it might be that this Feature only works with public property getters, not public fields:
Gets or sets the property to display for this ListControl.
public class USState
{
private string myShortName;
private string myLongName;
public USState(string strLongName, string strShortName)
{
this.myShortName = strShortName;
this.myLongName = strLongName;
}
public string ShortName
{
get
{
return myShortName;
}
}
public string LongName
{
get
{
return myLongName;
}
}
}
Of course I would also advise against making the list a part of the Type class. A simple Programm scope static would be better. If that is the case and as autoproties have have become a thing by now, this should be enough of a fix:
public class Type
{
public string Name { private set; get } ;
public string NameTag {private set; get };
public TypeList(string Name, string NameTag)
{
this.Name = Name;
this.NameTag = NameTag;
}
}
//use in the class of main, the form or some similar central point
static List<Type> TypeList = new List<Type>();
I have declared some static variables in my solution as below,
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static string ApproverlevelL1 = "M23";
public static string ApproverlevelL2 = "Cre";
public static string ApproverlevelL3 = "Free34";
public static string ApproverlevelL4 = "CDF";
public static string ApproverlevelL5 = "FM";
}
}
My question is, If i try to set it the like below then i get the error as :
An object reference is required for the non-static field, method, or
property
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static string ApproverlevelL1 = getLevel("1");
public static string ApproverlevelL2 = getLevel("2");
public static string ApproverlevelL3 = getLevel("3");
public static string ApproverlevelL4 = getLevel("4");
public static string ApproverlevelL5 = getLevel("5");
}
}
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
So how can i achieve this?
Looks like you are trying to call an instance method (non-static) from a static property.
Try making your method static:
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
Do you mean this:
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public static class Constants
{
public static string ApproverlevelL1 = getLevel("1");
public static string ApproverlevelL2 = getLevel("2");
public static string ApproverlevelL3 = getLevel("3");
public static string ApproverlevelL4 = getLevel("4");
public static string ApproverlevelL5 = getLevel("5");
private static string getLevel(string levelID)
{
string levelName;
logic here
return levelName;
}
}
}
If your issue is that you want the getLevel method to be in a different class, you could add a Function into your static class and override it with the method.
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static Func<string, string> getLevel = x => string.Empty;
// added get accessor to make these read only
public static string ApproverlevelL1 { get; } = getLevel("1");
public static string ApproverlevelL2 { get; } = getLevel("2");
public static string ApproverlevelL3 { get; } = getLevel("3");
public static string ApproverlevelL4 { get; } = getLevel("4");
public static string ApproverlevelL5 { get; } = getLevel("5");
}
public class WhateverClass
{
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
// call this before accessing the fields in your Constants class
public void Init()
{
Constants.getLevel = x => getLevel(x);
}
}
}
The only reason I can think of to do this is maybe you have two applications using this static class and they need to get the level differently. Maybe one uses actual constant values and another reads a database, etc.
If you don't require this then the simplest answer is to actually put the method into the class as a static method:
namespace SSPWAS.Utilities
{
public class Constants
{
public static string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
// added get accessor to make these read only
public static string ApproverlevelL1 { get; } = getLevel("1");
public static string ApproverlevelL2 { get; } = getLevel("2");
public static string ApproverlevelL3 { get; } = getLevel("3");
public static string ApproverlevelL4 { get; } = getLevel("4");
public static string ApproverlevelL5 { get; } = getLevel("5");
}
}
Your "constants" are not constant. Make them readonly if you want them to behave like constants while making use of initialising static members with values. You could also make them properties and use just the get accessor to call the getLevel method.
As others have pointed out you cannot call a non-static member from within a static member, without instantiating an instance of the non-static class.
Your getLevel method also needs to be in its own class. As it stands it doesn't belong to a class or namespace. If you want it in its own separate class then just set the method to static.
.NET naming conventions recommend you use Pascal Casing for methods. So rename your getLevel method.
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public static class Constants
{
// Use readonly static members
public static readonly string
ApproverlevelL1 = GetLevel("1"),
ApproverlevelL2 = GetLevel("2"),
ApproverlevelL3 = GetLevel("3"),
ApproverlevelL4 = GetLevel("4"),
ApproverlevelL5 = GetLevel("5");
// Or you could use the latest convenient syntax
public static string ApproverLevelL6 => GetLevel("6");
// Or you could use readonly properties
public static string ApproverLevelL7 { get { return GetLevel("7"); } }
private static string GetLevel(string levelId)
{
//... do logic
return "";
}
}
}
Or if you want the method in its own class:
public static class Constants
{
// Use readonly static members
public static readonly string
ApproverlevelL1 = Level.Get("1"),
ApproverlevelL2 = Level.Get("2"),
ApproverlevelL3 = Level.Get("3"),
ApproverlevelL4 = Level.Get("4"),
ApproverlevelL5 = Level.Get("5");
// Or you could use the latest convenient syntax
public static string ApproverLevelL6 => Level.Get("6");
// Or you could use readonly properties
public static string ApproverLevelL7 { get { return Level.Get("7"); } }
}
public class Level
{
public static string Get(string levelId)
{
//... do logic
return "";
}
}
public partial class OrderWS
{
private FulfillmentWS[] fulfillmentListField;
}
public partial class FulfillmentWS
{
private Customer fulfillingCustomerField;
private string fulfillingOutletIdField;
}
Above two classes are in two different .cs files.I'm creating object for OrderWs class and trying to assign value to fulfillingOutletIdField which is in another array class.
Need some logic to assign value to fulfillingOutletIdField variable which is in FulfillmentWS class.
Change private fields in FulfillmentWS to public properties.
public partial class OrderWS
{
private FulfillmentWS[] fulfillmentListField;
}
public partial class FulfillmentWS
{
public Customer fulfillingCustomerField { get; set; };
public string fulfillingOutletIdField { get; set; };
}
As you define fulfillingoutletIdField and other class as a private, it is not accessible due to protection level, either you can use protected or public (see below link for access modifiers for the variable scope).
Just change that thing and you can use it anywhere as above suggested.
public partial class FulfillmentWS
{
public Customer fulfillingCustomerField { };
public string fulfillingOutletIdField { };
}
Access Modifiers (C# Programming Guide)
https://msdn.microsoft.com/en-us/library/ms973875.aspx
http://www.c-sharpcorner.com/UploadFile/84c85b/default-scope-of-a-C-Sharp-class/
You can create a function:
public partial class OrderWS
{
private FulfillmentWS[] fulfillmentListField;
public void function()
{
...
}
}
Or you can use accessors get set:
public partial class OrderWS
{
private FulfillmentWS[] fulfillmentListField;
public FulfillmentWS[] _fulfillmentListField
{
get{return fulfillmentListField;}
set{fulfillmentListField = value;}
}
}
This is the way i'm assigning values to the variables
OrderWS WPObj = new OrderWS(); WPObj.fulfillmentList[1] = new FulfillmentWS(); WPObj.fulfillmentList[1].fulfillingOutletId = "1234";
I've an error at second line, saying Object reference not set to an instance of an object
You must create new instanceo of Array first.
WPObj.fulfillmentList = new FulfillmentWS[1];
Do you know about Properties?
public partial class FulfillmentWS
{
private Customer fulfillingCustomerField;
public Customer FulFillingCustomer
{
get { return fulfillingCustomerField; }
set { fulfillingCustomerField = value; }
}
private string fulfillingOutletIdField;
public string FulFillingOutletId
{
get { return fulfillingOutletIdField; }
set { fulfillingOutletIdField = value; }
}
}
Use public Properties to interact with your private fields.
Update:
Use Constructor to init array:
public partial class OrderWS
{
private FulfillmentWS[] fulfillmentListField;
public OrderWS(int length)
{
fulfillmentListField = new FulfillmentWS[length];
}
}
Then
OrderWS WPObj = new OrderWS(2); // Array length must be >= 2 if you want to access index 1.
WPObj.fulfillmentList[1] = new FulfillmentWS();
WPObj.fulfillmentList[1].fulfillingOutletId = "1234";
I've no experience of using C# but as part of one of our college modules we have to create a slot machine application. We created a Gambler class and I have to make a CheckBalance class where I will call the Token method from the Gambler class. But I get the error that is mentioned in the thread title.
Int tokens = Gambler.Tokens;
The above line is where I am getting my error.
This is my code:
enter code herenamespace CasinoClasslibrary
{
public class Gambler
{
public string Name { get; private set; }
public int Age { get; private set; }
public long CreditCardNum { get; private set; }
public int Tokens { get; public set; }
public string Username { get; private set; }
public string Password { private get; public set; }
public Gambler(string Name, int Age, long CreditCardNum, int Tokens, string Username, string Password)
{
this.Name = Name;
this.Age = Age;
this.CreditCardNum = CreditCardNum;
this.Tokens = Tokens;
this.Username = Username;
this.Password = Password;
}
}
public class Cashout : Gambler
{
public Boolean CheckBalance()
{
int tokens = Gambler.Tokens;
return true;
}
}
}
Since you are inheriting from Gambler I suspect that you need to access base.Tokens like:
public Boolean CheckBalance()
{
int tokens = base.Tokens; //here
return true;
}
Otherwise since Toakens is an instance member you have to create object of Gambler and then access it.
There are other errors in your code as well. You haven't defined a default (parameter less) constructor in your base class and you need to call the existing base constructor in your child class.
public class Cashout : Gambler
{
public Cashout()
: base("",0, 0, 1, "", "") //something like this
{
}
public Boolean CheckBalance()
{
int tokens = base.Tokens;
return true;
}
}
Because Cashout inherits from Gambler you can just do this. This is because the Cashout instance will have a Tokens property as well.
public class Cashout : Gambler
{
public Boolean CheckBalance()
{
int tokens = Tokens;
return true;
}
}
However, if you intended the method to be static, you will need an instance of Gambler to access that property and this should be passed into the static method as such.
public class Cashout : Gambler
{
public static Boolean CheckBalance(Gambler myGambler)
{
int tokens = myGambler.Tokens;
return true;
}
}
Finally, if you intended this Tokens property to be static itself, you need to declare it as such
public static int Tokens;
You may also want a static constructor to set it up.
Tokens is not static method but you try to access it through static construct (class level).
can make this work by declaring it static (although that's not likely what you want)
public static int Tokens { get; public set; }
or by instantiating Gambler
new Gambler().Tokens;
How would it be possible to reference an external string in an external class.
e.g.
Class1.cs:
MessageBox.Show(mystring);
Class2.cs:
public static void myMethod()
{
string mystring = "foobar";
// some logic here
}
If I right understood your question, you can do something like this:
public class2
{
public static string MyString
{
get {return "foobar"; }
}
}
public class1
{
public void DoSomething()
{
MessageBox.Show(class2.MyString );
}
}
Something like this?
public static class Foo
{
public const string FOO_CONST = "value";
}
public class Bar
{
public void Bar()
{
Console.WriteLine(Foo.FOO_CONST);
}
}
If you create a new instance of Class2 you can make MyString public or pull it out into a get method:
//In Class1
Class2 class2 = new Class2();
MessageBox.Show(class2.Mystring());
//In Class2
public string Mystring{ get; set; }
Or you could return the string from the method
public static string myMethod()
{
string myString = "foobar";
//logic goes here
return myString;
}
//In Class1
Class2 class2 = new Class2();
MessageBox.Show(class2.MyMethod());
Based on your clarification to your question:
I am trying to check a boolean value in a method in class2. E.g. if
the method run in class2 changes the boolean value in that method, the
method in class1 can check this and do some logic
You could do something like this:
class Class1 {
Class2 myClass = new Class2();
public void ActivityMethod() {
myClass.MethodThatMayChangeBoolean();
if(myClass.myBoolean) {
// Response to a truth change.
} else {
// Respond to a false change.
}
}
}
class Class2 {
public boolean myBoolean { get; }
public void MethodThatMayChangeBoolean() {
// Do stuff in here that may change boolean.
}
}
You will need to use Properties
private static string _mystring = "foobar";
public static string mystring
{
get { return _mystring ; }
set { _mystring = value; }
}
Or use auto properties and initialize their values in the static constructor of the class:
public static string mystring { get; set; }
public static MyStaticClass()
{
mystring = "foobar";
}