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?
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();
Related
I have a class library project, I want to create a variable and assign a value to it through MethodA() whose value can be access through MethodB().
Just like we have a session in ASP.NET.
I cannot pass as a parameter to MethodB() because MethodB() is being used in many places and if I change it, all the other methods will get affected.
Public Void MethodA()
{
string value ="Hello";
}
public Void MethodB()
{
-- I want to read the value which is set in MethodA()
}
I need to dispose the value as well after reading it in MethodB().
Both of these methods are in different classes inside the same project.
First try to create a property with a private setter:
public class A
{
public string Value { get { return MethodA(); } }
public string MethodA()
{
return "Hello";
}
public void MethodB()
{
var value = Value;
}
}
If you have two classes:
public class A
{
public string FooMethod()
{
return string.Empty;
}
}
public class B
{
public string BarMethod()
{
var result = new A().FooMethod();
return result;
}
}
You can get idea to handle your exception
public class test
{
public static int value = 0; //Global variable
public void MethodA()
{
//you can assign here as well
value++;
}
}
public class HomeController : Controller
{
test t = new test();
public IActionResult Index()
{
t.MethodA();
int d = test.value;
//you can assign here as well
test.value = 100;
int dd = test.value;
return View();
}
}
I am learning C# so I am still on the basics here. This is my code
class foo
{
protected int id;
protected string data;
static int nextId = 1;
public int Id
{
get { return id; }
}
public foo()
{
this.id = nextId++;
}
public foo(string somedata)
{
this.data = somedata;
this.id = nextId++;
}
}
This code works just fine for now. All objects will have a unique ID with them.
Problem is: I don't want the first ID to be 1, I want it to be the number on the first line of the file given as an argument to the application from the commandline. If no file is specified or the file does not exist, then it can be one. Is there a way to make a one-time method to set nextId so it cannot be tampered with outside of the class after it has been once set?
Duh... I guess this is the trick. Still, I'd like to know if there is some build in way to make variables that can only be set once.
public int nextId
{
set {if(nextId<1) nextId = value;}
}
You can implement static constructor, which assigns proper value to nextId before first usage of foo class:
using System.IO;
using System.Linq;
...
class foo
{
...
static int nextId;
// read-only property which however can be assigned in the constructor
public int Id {get;}
// This static costructor will be called once before 1st usage of foo class
static foo() {
//TODO: put the right file name here
string fileName = Environment.GetCommandLineArgs()[1];
nextId = int.Parse(File
.ReadLines(fileName)
.First());
}
public foo()
{
//Let's increment nextId in thread-safe manner
Id = Interlocked.Increment(ref nextId);
}
...
}
You can do this
class foo
{
private static int nextId = 1;
private static bool isNextIdSet;
public SetId(newId)
{
if (!isNextIdSet) nextId = newId;
isNextIdSet = true;
}
}
So the nextId can be set only once from outside the class.
UPDATE: if you prefer to use this with many variables, you can create a helper for this, such as
class SetOnlyOnce<T>
{
private bool isSet;
public T Value
{
get;
set
{
if (!isSet) Value = value;
isSet = true;
}
}
}
Then use it as
class Foo
{
public SetOnlyOnce<int> prop1 {get;set;}
public SetOnlyOnce<string> prop2 {get;set;}
}
class Bar
{
public Bar()
{
var foo = new Foo();
foo.prop1.Value = 2;
foo.prop1.Value = 3; // this doesn't set.
}
}
As an alternative to Dmitry's answer, you can define the initialization through a static method. I prefer avoiding static constructors unless multiple fields need to be initialized simultaneously.
using System.IO;
using System.Linq;
...
class foo
{
...
// The initialization will be called at some time before first use of nextId.
private static int nextId = GenerateInitialNextId();
// read-only property which however can be assigned in the constructor
public int Id {get;}
private static int GenerateInitialNextId() {
//TODO: put the right file name here
string fileName = Environment.GetCommandLineArgs()[1];
return int.Parse(File
.ReadLines(fileName)
.First());
}
public foo()
{
//Let's increment nextId is thread-safe manner
Id = Interlocked.Increment(ref nextId);
}
...
}
What I have is:
public static class IDs {
public static string someID { get; set; }
static IDs() {
log.info(someID);
// use someID here
}
}
public class otherClass {
public void otherMethod(string sym) {
IDs.someID = sym;
}
}
and then using an instance of otherClass like this:
otherClassInstance.otherMethod("someStringSymbol");
I dont have any build errors, but log.info(someID); is printing null.
I was expecting it to be someStringSymbol.
This is because the static constructor is called automatically before the first instance is created or any static members are referenced..
This means that when an instance of otherClass invokes IDs.someID = sym; the first operation that gets executed is the static constructor, i.e. the code inside static IDs().
At this point the static variable has not yet been initialized, and you are basically executing log.info(null);.
After the static constructor completes, the variable is initialized, so you should be able to see its value inside otherMethod, after the first reference of IDs.
Given the OP's requirement:
I want to use the value passed in someID in a switch statement
The solution could be to simply execute a static method whenever a new value is set, with the help of explicit getters and setters:
public static class IDs
{
private static string _someID; // backing field
public static string SomeID
{
get { return _someID; }
set
{
_someID = value;
DoSomethingWithSomeID();
}
}
private static DoSomethingWithSomeID()
{
// Use SomeID here.
switch (IDs.SomeID)
{
...
}
}
}
public class OtherClass
{
public void OtherMethod(string sym)
{
// This will set a new value to the property
// and invoke DoSomethingWithSomeID.
IDs.SomeID = sym;
}
}
DoSomethingWithSomeID will be invoked every time someone sets a new value to SomeID.
I dont think what you are trying to do is suited to static classes. I would try the following
public class IDs{
public string someID{ get; set; }
public IDs(string someId){
this.someID = someId;
log.info(this.someID);
//use someID here
}
}
pulic class otherClass{
public otherMethod(string sym){
IDs id = new IDs(sym);
}
}
public class anotherClass{
//access instance of otherClass in wrp and call otherMethod()
wrp.otherMethod("someStringSymbol")
}
How do I use the propfull tab tab gadget in visual studio?
Class Foo
{
public int regirsterR0
{
get { return R0; }
set { R0 = value; }
}
}
How would I use the get and set methods from another class? Let's say this method is in a class called foo. How would I use the get and set from foo in goo?
Class Goo
{
Foo g= new Foo();
g.regirsterR0.Get?????
}
First, thats called a snippet (and there are a bunch of others!). This one creates a full property (MSDN) definition.
To answer your question; you just use it as if it were a field:
var test = g.Register0; //invokes get
g.Register0 = 2; //invokes set
get and set are nice method abstractions that are called when the associated property is accessed or assigned to.
Note that you don't even need the snippet; you could have used an auto-property:
public int RegisterR0 { get; set; } //Properties are PascalCase!
Get and Set is not a value or method. Actually they are property like a control mechanism. (encapsulation principle)
for ex:
var variable = g.Register0; // so it is get property. // like a var variable = 5;
g.Register0 = 5; // so it is set property.
Look msdn explaining.
You just forgot create method. :-)
class Foo
{
private int regirsterR0;
public int RegirsterR0
{
get { return regirsterR0; }
set { regirsterR0 = value; }
}
}
class Goo
{
Foo g = new Foo();
void myMethod()
{
// Set Property
g.RegirsterR0 = 10;
// Get property
int _myProperty = g.RegirsterR0;
}
}
If you want initialize new object of class Foo with Value you can:
class Foo
{
private int regirsterR0;
public int RegirsterR0
{
get { return regirsterR0; }
set { regirsterR0 = value; }
}
}
class Goo
{
Foo g = new Foo() { RegirsterR0 = 10 };
void myMethod()
{
Console.WriteLine("My Value is: {0}", g.RegirsterR0);
}
}
But usualy you don't need use propfull. Will be fine if you use prop + 2xTAB. Example:
class Foo
{
public int RegirsterR0 { get; set; }
}
class Goo
{
Foo g = new Foo() { RegirsterR0 = 10 };
void myMethod()
{
Console.WriteLine("My Value is: {0}", g.RegirsterR0);
}
}
Wrok the same and easer to read.
How would you share the same object between two other objects? For instance, I'd like something in that flavor:
class A
{
private string foo_; // It could be any other class/struct too (Vector3, Matrix...)
public A (string shared)
{
this.foo_ = shared;
}
public void Bar()
{
this.foo_ = "changed";
}
}
...
// inside main
string str = "test";
A a = new A(str);
Console.WriteLine(str); // "test"
a.Bar();
Console.WriteLine(str); // I get "test" instead of "changed"... :(
Here, I don't want to give a ref to the Bar method. What I want to achieve is something that would look like that in C++:
class A
{
int* i;
public:
A(int* val);
};
A::A (int* val)
{
this->i = val;
}
I read there is some ref/out stuff, but I couldn't get what I'm asking here. I could only apply some changes in the methods scope where I was using ref/out arguments...
I also read we could use pointers, but is there no other way to do it?
This has nothing to do with sharing objects. You passed a reference to a string into the A constructor. That reference was copied into the private member foo_. Later, you called B(), which changed foo_ to "changed".
At no time did you modify str. str is a local variable in main. You never passed a reference to it.
If you had wanted to change str, you could have defined B as
public void Bar(ref string s)
{
this.foo_ = "changed";
s = this.foo_;
}
Consider:
public class C
{
public int Property {get;set;}
}
public class A
{
private C _c;
public A(C c){_c = c;}
public void ChangeC(int n) {_c.Property = n;}
}
public class B
{
private C _c;
public B(C c){_c = c;}
public void ChangeC(int n) {_c.Property = n;}
}
in main:
C myC = new C() {Property = 1;}
A myA = new A(myC);
B myB = new B(myC);
int i1 = myC.Property; // 1
myA.ChangeC(2);
int i2 = myC.Property; // 2
myB.ChangeC(3);
int i3 = myC.Property; // 3
Wrap your string inside a class. You need to do this because strings are immutable. Any attempt to change a string actually results in a new string.
class Foo {
class StringHolder {
public string Value { get; set; }
}
private StringHolder holder = new StringHolder();
public string Value {
get { return holder.Value; }
set { holder.Value = value; }
}
public Foo() { }
// this constructor creates a "linked" Foo
public Foo(Foo other) { this.holder = other.holder; }
}
// .. later ...
Foo a = new Foo { Value = "moose" };
Foo b = new Foo(a); // link b to a
b.Value = "elk";
// now a.Value also == "elk"
a.Value = "deer";
// now b.Value also == "deer"
I would split my answer to 2 parts:
1) If the variable is a reference type than it is already shared since you pass its reference to all interested objects. The only thing you should pay attention is that the reference type instances are mutable.
2) If the variable is a value type than you would have to use ref or out or some wrapper that is mutable and you can change the value inside the wrapper using a method or a property.
Hope that helps.
You need to pass the paramter as a reference to your method,
class A
{
private string foo_; // It could be any other class/struct too (Vector3, Matrix...)
public A(string shared)
{
this.foo_ = shared;
}
public void Bar(ref string myString)
{
myString = "changed";
}
}
static void Main()
{
string str = "test";
A a = new A(str);
Console.WriteLine(str); // "test"
a.Bar(ref str);
Console.WriteLine(str);
}
When a variable is a string, it is a reference.
Try to clone the string. http://msdn.microsoft.com/en-us/library/system.string.clone.aspx