Public variable access - c#

I have a class called Global.cs:
public class Global
{
private string id= string.Empty;
public string Id
{
get { return id;}
set { id= value; }
}
}
Now in the Main class,
public class Main
{
public Global objGlobal;
protected void Page_Load(object sender, EventArgs e)
{
objGlobal= new Global();
objGlobal.id="XX001";
}
public void Setdata()
{
// Trying to access objGlobal.id value here but it's null
}
}
What am I missing?

Shouldn't you always be getting/setting "Id" rather than "id". As "id" is private.

Well, your XX class instance is more than one time.
If you need to persist some user-retalive info, try storing it into the SessionState.
If you need to just have the static class with some static data, add the static keyword to both class and its members.

Related

How can I access my method from another class

I'm very new to c#, I started a few days ago, so please excuse me if it is basic.
I have two forms, the first one is like a login page, where someone enters their name. On my "Info.cs" class, it reads this name via a setter, into a variable, and my Getter called "GetCardName" returns this Name. I now made a new form where I want to access this name via the GetCardName getter, just dont know how too. Heres the code :
Here is some of the "info.cs" class code:
private string CardName { get; set; } = "";
public string GetCardName()
{
return this.CardName;
}
public void SetName(string name = "")
{
this.CardName = name;
}
And here is the code from the other form that is just trying to call GetCardName():
private void Form2_Load(object sender, EventArgs e)
{
lblWelcome.Text = Info.GetCardName();
}
When creating Form2 you need also pass it reference to the other form to get its properties.
So when creating and showing Form1 you should also create Form2 to pass that reference. Example (not tested) code:
var form1 = new Form1();
var form2 = new Form2(form1);
form1.Show();
and Form2 should be like:
public class Form2
{
private Form1 _form1;
public Form2(Form1 form1)
{
_form1 = form1;
// ... other initialization code
}
// ... other class declarations
}
General solution is: you need to persist reference to the Form1 being shown to the user and then pass that reference to Form2 whenever you create it.
You have two options :
you can create an instance of the class that you want to call
EX : Info infoVar = new Info(); (now you can use infoVar to call any methods of the Info.cs class)
you can make Info class a STATIC class (probably not what you want to do, but still helpful for the future perhaps) This makes it possible to call the info class directly without having to create a variable of that class but has some drawbacks. (more info here)
There is few ways to achieve what you want:
Public static property:
public class Info
{
public static string CardName { get; set; } = string.Empty;
}
You can access it or set value to it directly by:
private void Form2_Load(object sender, EventArgs e)
{
// Set
Info.CardName = "Some name";
// Get
lblWelcome.Text = Info.CardName;
}
Public non-static property:
public class Info
{
public string CardName { get; set; } = string.Empty;
}
You can access it or set value to it directly too, but need to create Info class instance before:
private void Form2_Load(object sender, EventArgs e)
{
Info info = new Info();
// Set
info.CardName = "Some name";
// Get
lblWelcome.Text = info.CardName;
}
Private static field with separated public static Get and Set methods:
public class Info
{
private static string cardName = string.Empty;
public static string GetCardName()
{
return cardName;
}
public static void SetCardName(string name = "")
{
cardName = name;
}
}
You can access GetCardName and SetCardName without creating Info class instance:
private void Form2_Load(object sender, EventArgs e)
{
// Set
Info.SetCardName("Some name");
// Get
lblWelcome.Text = Info.GetCardName();
}
Private non-static field with separated public non-static Get and Set methods:
public class Info
{
private string cardName = string.Empty;
public string GetCardName()
{
return cardName;
}
public void SetCardName(string name = "")
{
cardName = name;
}
}
You can access GetCardName and SetCardName after creating Info class instance:
private void Form2_Load(object sender, EventArgs e)
{
Info info = new Info();
// Set
info.SetCardName("Some name");
// Get
lblWelcome.Text = info.GetCardName();
}
Difference between fields and properties was pretty nice explained here: What is the difference between a field and a property?. In short, properties are "wrappers" over fields, which usually are private and you can't access to them directly or modify. It is a part of Member Design Guidelines. Also properties allow to add some validations through property setter to be sure that valid value is stored at cardName field, e.g.:
public class Info
{
private string cardName = string.Empty;
public string CardName
{
get => cardName;
set
{
// Check that value you trying to set isn't null
if (value != null)
cardName = value;
// Or check that name is not too short
if (value.Length >= 3) // Card name should be at least of 3 characters
cardName = value;
}
}
}
info myInfo=new info();
lblWelcome.Text = myInfo.GetCardName();

C# Class With Sub Class And Inheritance: setting value in inherited class

I am fairly new to C# so be gentle.
My end goal is to have a few different types of classes for inheritance (example below: Level). These inherited classes do two things, have .Value property with different setters depending on the class, and a .Action method, unique for every instance so it is an override.
Question: how do i set the .Value property from a method on the class. This is the line of code (line 27) that does not work from the example below. And I don't understand why.
Potentiometer.Value = Convert.ToDouble(data);
// Code taken from https://dotnetfiddle.net/YNJpjf
using System;
namespace Main {
class Program
{
static Device device = new Device();
static void Main(string[] args)
{
device.HandleDataUpdate("50");
}
}
public class Device
{
public class Potentiometer : Level
{
public override void Action()
{
Console.WriteLine("value is at: {0}", this.Value);
}
}
public void HandleDataUpdate(String data)
{
Potentiometer.Value = Convert.ToDouble(data);
}
}
public class Level
{
private Double thisValue;
public Double Value
{
get => thisValue;
set
{
if (thisValue != value)
{
thisValue = value;
Action();
}
}
}
public virtual void Action()
{
}
}
}
Give Level a protected abstract method OnSetValue, forcing each subclass to override it. Now the setter of Value can call OnSetValue before the value is set:
public class Level {
private double val;
public double Value {
get {
return val;
}
set {
OnSetValue(value);
val = value;
}
}
protected abstract void OnSetValue(double val);
...
}
public class Potentiometer : Level {
protected void OnSetValue(double val) {
...
}
}
You need to create an instance of Potentiometer.
https://dotnetfiddle.net/8JQDyO
You're trying to set value of class field, which is impossible, not of object's field. You have to make instance of Potentiometer inside the Device, if you want to do this , you could make method or change code logic.

C# How to Restrict write of a global variable to only the class where it is initialized (so other classes only can read it)?

As the title states I'm looking for a way how to solve following:
namespace Test
{
public partial class SetVariable : Form
{
public string test = "";
public SetVariable()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
test = "test"
}
}
}
and in a second form I want to read it, but also want to restrict the user from making any changes to the variable (by accident or on purpose), as all the variables are only to be set in the SetVariable Form, and then be used across all other forms that are planned.
namespace Test
{
public partial class GetVariable : Form
{
public GetVariable()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
if (SetVariable.test == "test")
{ //doSomething;}
}
}
}
}
If I make the variable a public readonly, than I cant write to it in the form where its supposed to be written. Is there another way of initalizing a global variable which is only changable in the form where its created?
Thanks in advance.
Change:
public string test = "";
to:
public string test { get; private set; }
Also see https://stackoverflow.com/a/3847982/34092 .
Make public property private set.
public partial class SetVariable : Form
{
public string Test {get; private set;}
//Just in case if you want to set value to Test property from other class.
//If you want Test property readonly to other
//class you don't need this method.
public void SetTest(string test)
{
Test = test;
}
}
public class Main
{
SetVariable sv = new SetVariable();
sv.SetTest("Some Value"); //unwanted to scenario. Just in case if you want
//read Test value
string testValue = sv.Test; //allowed
//set Test value
sv.Test = "Other value"; //not allowed.
}

Create a default value when no value is set into class properties

I have a class that has multiple properties. What I want to have is a value set to a particular property if there is no value passed to it. For instance, if txtFather.Text is blank, then the _theFather property of a class should have a default value of "N/A". Here is the code I have so far:
class StudentModel
private string _theFather = "N/A";
public string SetFather
{
get { return _theFather; }
set { _theFather = value; }
}
public void InsertStudent(StudentModel student)
{
MessageBox.Show(_theFather);
}
class AddStudent
private void button1_Click(object sender, EventArgs e)
{
var sm = new StudentModel()
{
SetFather = txtFathersName.Text
};
sm.InsertStudent(sm);
}
If I place a value in the txtFather.Text, I get the its value in the StudentModel Class but if I leave the txtFather.Text blank, I don't get the "N/A" value. I just get a blank or no value at all.
Thanks for your help.
I would encapsulate the logic within the StudentModel class by checking the value being passed to the setter, and only updating your backing field if the string is not null or whitespace.
public string SetFather
{
get { return _theFather; }
set {
if(!string.IsNullOrWhiteSpace(value))
{
_theFather = value;
}
}
}
This way you only have the logic in a single place. If you modify your class' consuming code, then you have to remember to change it everywhere.
You should set the property only if a string is typed, like this:
private void button1_Click(object sender, EventArgs e)
{
var sm = new StudentModel();
if (!string.IsNullOrEmpty(txtFathersName.Text))
sm.SetFather = txtFathersName.Text;
sm.InsertStudent(sm);
}

How to call value from getter and setter method

I have a class called nyoba, i tried to enter value of textBox1.Text to eek.konsentrasi.
And I don't have any idea to call value of eek.konsentrasi from another class. Anybody knows? please help me.
public class nyoba
{
private string Konsentrasi;
public string konsentrasi
{
get
{
return Konsentrasi;
}
set
{
Konsentrasi = value;
}
}
public void njajal(string hehe)
{
}
}
private void button1_Click(object sender, EventArgs e)
{
nyoba eek = new nyoba();
eek.konsentrasi = textBox1.Text;
}
public class caller
{
//how to get eek.konsentrasi variable?
}
As first, your class names should always be pascal case (first letter uppercase). Also your public property should be pascal case.
Then your Nyoba class and its property Konsentrasi are not static, means you have to initiate the class as object before you can access it's non static property.
Nyoba n = new Nyoba();
string s = n.Konsentrasi;
To access the same instance you should not create the instance inside of the button click event. Place your Nyoba instance somewhere you can access to in the form and in the Caller class.

Categories