public class variables {
public static int edit{ get;set; }
}
And also tried:
public static int edit = 0;
public static int edit { get; set; }
public static int edits { get { return edit; } }
Using the form
form:form1 {
// Changing the value of variable to 1
private void Form1_Load(object sender, EventArgs e) {
variables.edit=1;
}
// Calling the new form where I'll use its value
private void Button_Click(object sender, EventArgs e){
form2 A=new form2();
A.Show();
}
}
form:form2{
// Showing the value of the variable in a message box
private void Form2_Load(object sender, EventArgs e){
MessageBox.show(variables.edit.ToSting());
}
}
The Message in all cases returned 0 least that call again. I need to know how to make the values initialize step as the first. I have to tab Use the many variable that keep data from one form to another and use in the load.
Make sure your class variables is static, not only the fields/properties:
public static class variables {
public static int edit = 0;
}
Another source of problem with static classes is when you use one field/property when setting another:
public static class variables {
public static int someValue = 2;
public static int other = someValue + 3;
}
AFAIK, you can't be sure of what field/property will be set first by the static constructor at runtime, unless you set the values in the static constructor, like this:
public static class variables {
static variables() {
someValue = 0;
other = someValue + 3;
}
public static int someValue;
public static int other;
}
If you are declaring static fields/properties in a really non-static class, check for the problem above, and if nothing else is changing the static field/property in another place, even inside the non-static class.
Related
I wrote the code below and i want to access the private varibale in another class, i created instance of the class and tried to access it but couldn't. can someone point out what I did wrong in the code below?
using System;
namespace lab_first
{
public class AccessModifiers
{
private int Abc { get; set; }
private int bcd { get; set; }
}
class Program
{
static void Main(string[] args)
{
var acc = new AccessModifiers();
Console.WriteLine(acc.Abc)
}
}
}
You make members private so that nobody outside the class can access them.
This goes inline with the principle of information hiding.
Your example should look like this:
public class AccessModifiers
{
// You can only access this inside of the class AccessModifiers
private int Abc { get; set; }
internal void SetValue(int x){
// Access possible, because SetValue() is inside the same class
Abc = x;
}
internal int GetValue(){
// Access possible, because GetValue() is inside the same class
return Abc;
}
}
class Program
{
static void Main(string[] args)
{
var acc = new AccessModifiers();
// Abc is never modified directly, only indirectly.
acc.SetValue(5);
Console.WriteLine(acc.GetValue());
}
}
However, there is still a way to access the private member. It's called Reflection. However, note that private variables are considered an implementation detail and might change at any time, so you can't rely on it. E.g. someone might change the name from Abc to def and your Reflection-based approach fails.
You can either change private to internal or public in this case.
Another way is declaring the variables in the class as private and using C# Properties in the class to set and get the values of variables. this is called encapsulation which is a protective shield that prevents the data from being accessed by the code outside this shield).
public class AccessModifiers
{
private int _abc { get; set; }
private int _bcd { get; set; }
public int Abc
{
get
{
return _abc;
}
set
{
_abc = value;
}
}
public int Bcd
{
get
{
return _bcd;
}
set
{
_bcd = value;
}
}
}
I'm just learning C# after using VBA for many years, I'm not a professional and this is something I do in my leisure. I'm looking to replicate the logic of using a public variable that can be accessed from a method and incremented by one each time when clicking button cmdPublicVartest , Below is the code I have so far, but am getting the error
An object reference is required for the non-static field, method, or property, in the publicvar class, it looks because it's a static class, however if I remove it from a static class, I would have to call an instance of the class on the button cmdPublicVartest. Is there a way I can keep publicvar a static class, so I don't have to do an instance of the class on the button?
namespace testDB
{
public partial class Database : Form
{
public string publictest = "public test";
public int pUblicint = 0;
public static void PublicVar()
{
MessageBox.Show(publictest + pUblicint);
pUblicint++;
}
private void cmdPublicVartest_Click(object sender, EventArgs e)
{
testDB.Database.PublicVar();
}
}
}
You cannot access non-static fields from a static method because they belong to an instance of the class, and when calling a static method you do not have an instance.
You could either make the fields static like this
public partial class Database : Form
{
public static string publictest = "public test";
public static int pUblicint = 0;
public static void PublicVar()
{
MessageBox.Show(publictest + pUblicint);
pUblicint++;
}
private void cmdPublicVartest_Click(object sender, EventArgs e)
{
testDB.Database.PublicVar();
}
}
Or make the method non-static like this
public partial class Database : Form
{
public string publictest = "public test";
public int pUblicint = 0;
public void PublicVar()
{
MessageBox.Show(publictest + pUblicint);
pUblicint++;
}
private void cmdPublicVartest_Click(object sender, EventArgs e)
{
PublicVar();
}
}
Just revise your code to this:
namespace testDB
{
public partial class Database : Form
{
public string publictest = "public test";
public int pUblicint = 0;
public void PublicVar()
{
MessageBox.Show(publictest + pUblicint);
pUblicint++;
}
private void cmdPublicVartest_Click(object sender, EventArgs e)
{
PublicVar();
}
}
}
While PublicVar() is static, the fields it references (publictest, pUblicint) are not. You have to make them static as well or make PublicVar() not-static.
I have 2 classes where 1 class is like the main class and I have a secondary class which is instantiated from the main class. How am I able to use the main class' method from the secondary class. Here's code to give an illustration of what I want.
public class MainClass
{
private SecondaryClass secondaryClass;
private int testValue;
public MainClass()
{
this.secondaryClass = new SecondaryClass();
testValue = 0;
}
public void updateTestValue (int val)
{
testValue = val;
}
}
public Class SecondaryClass : Form
{
public SecondaryClass()
{
}
private void button1_click(Object sender, EventArgs e)
{
// I want to be able to do this:
primaryClass.updateTestValue(100);
}
}
You can make classes communicate without having one derive from another.
public class MainClass
{
private SecondaryClass secondaryClass;
private int testValue;
public MainClass()
{
this.secondaryClass = new SecondaryClass(this.UpdateTestValue);
testValue = 0;
}
public void UpdateTestValue (int val)
{
testValue = val;
}
}
public class SecondaryClass : Form
{
private Action<int> UpdateValue { get; }
public SecondaryClass(Action<int> updateValue)
{
this.UpdateValue = updateValue;
}
private void button1_click(Object sender, EventArgs e)
{
this.UpdateTestValue(100);
}
}
In this organization, primary class is passing a delegate to its own instance-level method when it creates the secondary class. Secondary class calls that delegate when appropriate, without ever knowing what function that is.
This is the example of the callback pattern.
There are other variants of the same idea. For example, primary class could implement an interface which defines the UpdateValue method. Then, it passes this reference to every object which needs access to that method. Other objects, like an object of secondary class, would then simply call a method of that interface, once again not knowing that it is in fact the primary class they are referencing.
public interface IListener
{
void Update(int value);
}
public class MainClass : IListener
{
private SecondaryClass secondaryClass;
private int testValue;
public MainClass()
{
this.secondaryClass = new SecondaryClass(this);
testValue = 0;
}
public void Update(int val)
{
testValue = val;
}
}
public class SecondaryClass : Form
{
private IListener Listener { get; }
public SecondaryClass(IListener listener)
{
this.Listener = listener;
}
private void button1_click(Object sender, EventArgs e)
{
this.Listener.Update(100);
}
}
The price of this solution is one additional type in the system (interface IListener), and the benefit is that you can avoid working with delegate syntax. Delegates have a drawback that their arguments have no names, and therefore you can easily make a bug if you mix them up.
public class MainClass: Form
{
private int testValue;
public MainClass()
{
testValue = 0;
}
public void updateTestValue (int val)
{
testValue = val;
}
}
public class SecondaryClass : MainClass
{
public SecondaryClass()
{
}
private void button1_click(Object sender, EventArgs e)
{
// I want to be able to do this:
updateTestValue(100);
}
}
A class can only have one base class
What you could do is move the :Form base class up to the primary class and then from your secondary class have it's base class as Primary class and use the functions as follows.
public class PrimaryClass : Form
{
private int testValue;
public void PrimaryClassMethod()
{
Console.WriteLine("Method from Primary Class");
}
public void UpdateTestValue (int val)
{
testValue = val;
}
}
public class SecondaryClass : PrimaryClass
{
public void CallPrimaryClassMethod()
{
this.PrimaryClassMethod();
this.UpdateTestValue(10000);
}
}
https://dotnetfiddle.net/PC2WVu
So what i have is basically this:
public partial class ShowList : UserControl
{
public int count;
private static LoadMovies lm = new LoadMovies();
public List<Movie> movieList = lm.GetMovieList();
public ShowList(string genreTitel)
{
InitializeComponent();
......
......
Load(genreTitel)
}
public void Load(string genreTitel)
{
lm.ReadMoviesToList();
string picturepath = Environment.CurrentDirectory + #"\Pictures" + #"\Pictures\";
IEnumerable<Movie> genreMovieList =
movieList.Where(m => m.MovieGenres.Contains(genreTitel) && m.MovieNumberOfRatings > 80).Take(20);
Movie movie1 = genreMovieList.ElementAt(count);
label29.Text = movie1.MovieName;
pictureBox9.Image = Image.FromFile(picturepath + movie1.MovieId + ".jpg");
label24.Text = "Rating: " + Math.Round(movie1.MovieAverageRating, 2);
}
private void Btn_Click(object sender, EventArgs e)
{
count++;
//HERE I NEED SOME CODE TO RELOAD LOAD-METHOD.
}
What i have tried, is to just write Load(); but as the method needs the genreTitel. And i cant reach the genreTitel.
How do i increment count, and reload Load(genreTitel) when clicking on button?
Save genreTitel (title?) to a private variable. In the constructor assign the passed in to the new private variable, then you can access it from the Btn_Click.
Declare a string genreTitel (or name it whatever you want) under your movielist declaration and then before you call Load(genreTitel) the first time in the constructor, do:
this.genreTitel = genreTitel.
This way you have a genreTitle variable accessible to the rest of the class
Assuming you're getting genreTitel from some form field, you can access that field in your Click Event Handler.
Ergo, where you tried to put simply Load(), use Load(formField.Text).
Edit: Just noticed that ShowList(string genreTitel) was a constructor, not a method.
In that case, instantiate a private variable and assign genreTitel to it in your constructor.
do like this
//declare the class level variable like this
private string mgenretitle;
public ShowList(string genreTitel)
{
// initialize the variable over here like this
mgenretitle = genreTitel;
InitializeComponent();
......
......
Load(genreTitel)
}
and then use it over here
private void Btn_Click(object sender, EventArgs e)
{
count++;
// call your load method over here
Load(mgenretitle);
//HERE I NEED SOME CODE TO RELOAD LOAD-METHOD.
}
This is a followup to a previous question: C# Static event null from within class
I have a class like this:
public class PlaylistModel {
public static event EventHandler PlaylistLoadError;
public static int myInt;
public static void LoadPlaylist()
{
try
{
// do some stuff, simulate exception
throw new InvalidOperationException();
}
catch(InvalidOperationException ex)
{
EventHandler handler = PlaylistLoadError;
if(handler != null)
{
PlaylistLoadError(null, null);
}
}
}
}
Else where in the program, I am setting the PlaylistLoadError EventHandler, like so:
public class MainPage {
public MainPage() {
PlaylistModel.PlaylistLoadError += MyErrorHandler;
PlaylistModel.myInt = 5;
}
public static void MyErrorHandler(object sender, EventArgs e)
{
Debug.WriteLine("There was an error");
}
}
Now, inside of LoadPlaylist, PlaylistLoadError is null and myInt is 0, despite setting them elsewhere. Later, when I create an instance of PlaylistModel, PlaylistLoadError and myInt are the correct values. So my question is this - do static functions of a class somehow access different versions of static class variables? I have checked the memory addresses of the static variables, and they are indeed different depending on if I'm inside of a non-static vs. a static function.
Static variables are static and will remain the same while the program is running unless something is called to change it.
If you want to find out what is happening I would change the field to:
private static int _myInt;
and then add:
public static int myInt
{
get { return _myInt; }
set { _myInt = value; }
}
and then add a break point at on set so you can find out when it is being changed.