I want to access a string from one class to another. I have used the property method as follows -
Myclass.cs
public class MyClass
{
private string _user;
public string user
{ get { return this._user; } set { this._user = value; } }
}
consumption.aspx.cs
I am assigning the value to user in a function
MyClass m = new MyClass();
m.user = "abc"
Now when I try to use this value in my another function which is called after this value is assigned
RawDal.cs
MyClass m = new MyClass();
string x = m.user;
I get empty value... How to do it?
You can access all the variables by using the subclass object, and you don't have to create an object of the parent class. This scenario only happens when the class is extended; otherwise, the only way to access it is by using the subclass.
Variable defined inside the class: For Example – self. var_name. If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.
A static variable can be accessed inside any other class using the class name.
value" it must be a class variable but in your code it is a local variable inside "method()". So you either need to return "value" from "method()" and print it by "obj2. method()" or move the declaration of "value" to class level, initialize it and then print it "obj2. value".
As already mentioned in the comments you are creating two separate instances of MyClass
which results simplified in something like:
int a;
a = 3;
int b;
Console.WriteLine("a: " + b); //<-- here it should be obvious why b is not 3
You can work around this in 3 ways:
1) Use the same instance of MyClass
for the second call, but in this case you need to be in the same scope or pass the instance on to the new scope.
2) Make the property/member static:
public class MyClass
{
public static string User { get; set; } //the "static" is the important keyword, I just used the alternative property declaration to keep it shorter
}
Then you can access the same User
value everywhere via MyClass.User
.
3) Use a singleton:
public class MyClass
{
private static MyClass instance = null;
public static MyClass Instance
{
get
{
if(instance == null)
instance = new MyClass();
return instance;
}
}
public string User { get; set; }
}
Then you can access it via MyClass.Instance.User
.
There are possibly some more solutions, but these are the common ones.
You are not using the same instance. Try
public class MyClass
{
private string _user;
public string user
{ get { return this._user; } set { this._user = value; } }
}
public string YourFunction()
{
MyClass m = new MyClass();
m.user = "abc"
return m.user;
}
If all you want to return is a string try something like
string x = YourFunction();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With