I want to get a reference to an existing class variable using a string. I have seen some examples of similar things but can seem to figure this one out.
Please help with the commented section!
public class MyClass
{
public int myInt;
public MyClass( int i)
{
myInt = i;
}
}
void Start ()
{
MyClass myclass = new MyClass(1);
MyClass myOtherClass = //Should be equal to myClass BUT I want to use the string "myClass" to reference it.
}
Local variables cannot be accessed by string name, even using reflection. One option is to store them in a dictionary:
var dict = new Dictionary<string, MyClass>();
dict.Add("myClass", myClass);
string varName = "myClass";
MyClass myOtherClass = dict[varName];
But it's not clear at all why you want to access it by string name. I suspect there's a better solution for your real problem.
Though the question is kind of weird, but here is the stupid solution:
var instances = new Dictionary<string, MyClass>();
MyClass instance= new MyClass(1);
//the string "instance" can be replaced with "nameof(instance)" using C# 6.0
instances.Add("instance", instance);
To access this instance by name:
MyClass myOtherInstance = instances["instance"];
Wierd question, curious to know if this is what you wanted:
public class MyClass
{
public int myInt;
public MyClass(int i)
{
myInt = i;
}
}
public class Starter
{
private MyClass myclass;
public void Start()
{
myclass = new MyClass(1);
var type = this.GetType();
var variable = type.GetField("myclass", BindingFlags.NonPublic | BindingFlags.Instance);
MyClass myOtherClass = (MyClass)variable.GetValue(this);
}
}
Related
Haven't found a definite answer on this so I'm going to ask it here. Sorry if I missed something.
Say we have this class
internal class MyClass
{
public MyClass()
{
}
private string my_field;
public string MyField
{
get { return my_field; }
set { my_field = value; }
}
}
and we create a List<MyClass> like this and populate it with testing info
List<MyClass> my_list = new List<MyClass>();
private void TestFunction()
{
MyClass mc = new MyClass();
mc.my_field = "test1";
my_list.Add(mc);
}
My question is, will IndexOf() return the real index of mc if I create an identical MyClass object with the same my_field value? If not, why ?
private void SearchList()
{
MyClass mc = new MyClass();
mc.my_field = "test1";
int index = my_list.IndexOf() // WILL THIS RETURN THE INDEX OF THE PREVIOUSLY ADDED "mc" OBJECT
}
I will post this here as it may help someone somewhere.
Thanks to the comments I understood how IndexOf() works.
Basically the method uses the Equals() method to find the matching object and return the index of the provided object.
Here is the relevant documentation from msdn
List.IndexOf Method
public class testClass
{
testClass x = null;
public testClass()
{
x = this;
}
~testClass()
{
System.Console.WriteLine("I was destroyed");
}
}
public static class objectInMemory
{
public static int Main(string[] args)
{
testClass a = new testClass();
a = null;
System.Console.WriteLine("a=null");
System.Console.WriteLine("something");
System.Console.WriteLine("last line");
return 0;
}
}
So.. In the code, how can I assign the instantiated testClass object to another variable after "a = null;" For example let "b = thatObject'sAddress;"?
It is not a problem, just came across my mind.
You could use this to get a pointer to your object and use the debugger to check what you want to know:
Memory address of an object in C#
Garbage Collector basics can be looked up here:
https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals
I would like to pass values from one class file to another class.
E.g:
Step1:
Class1.cs
public class Class1
{
public string LogedInPerson { get; set; }
public string Name
{
get { return this.LogedInPerson; }
set { this.LogedInPerson = value; }
}
}
Step2:
Value has been assigned in below method:
test.xaml.cs
public void assignValue()
{
Class1 obj = new Class1();
obj.LogedInPerson = "test123";
}
Step3:
I would like to get "test123" values from Class2.cs.
E.g:
public void test()
{
string selected_dept = ?? //How to get "test123" from here.
}
You can have variables class that includes public variables. Define instance of class1 in variables class .
public static class1 myclass=new class1();
in test.xml.cs set value
public void assignValue()
{
myclass.LogedInPerson = "test123";
}
in class2.cs
public void test()
{
string selected_dept = myclass.LogedInPerson;
}
Initialize Class1 outside assignValue() methos
Class1 obj = new Class1();
public void assignValue()
{
obj.LogedInPerson = "test123";
}
public string returnValue()
{
return obj.LogedInPerson;
}
if your second class name test.xaml then call it like this, but I don't think you can use class name test.xaml so use a nice name instead there eg: Class2
public void test()
{
test.xaml test = new test.xaml();
test.assignValue();
string selected_dept = test.returnValue(); //How to get "test123" from here.
}
I believe this question is more on the topic of basic Object Oriented Programming principles, not so much about WPF specific features. Therefore, I will provide you a non-WPF specific answer, as it will allow me to address your question in the most direct way.
In OOP, a method can return a result to the caller. So, for instance,
public string GetReturnObject(){
return "This is a return object";
}
You can create a new object and pass it back to the caller,
public void Test(){
string data = GetReturnObject();
}
And now data will be assigned the object that was returned from the method that Test() called. So, if you modify your AssignValue method by adding a return type and passing the instantiated Class1 object back to the caller, you will have the answer you need
public Class1 assignValue()
{
Class1 obj = new Class1();
obj.LogedInPerson = "test123";
return obj;
}
Hope that helps.
I need to have a class for Variables and Methods for the sake of manageability.
The problem is I am not sure how I can access the value of the variable assigned in the method class.
Here is the variable class, it just holds variables:
namespace Classes
{
class MyVariableClass
{
public string MyVariable { get; set; }
}
}
Here is the method:
I am calling an instance of the variable class in the method class so that I can assign the variable to the values of the method.
namespace Classes
{
class MyMethods
{
MyVariableClass myVarClass = new MyVariableClass();
public void DoSomeStuff(string myString1, string myString2)
{
myVarClass.MyVariable = (!string.IsNullOrEmpty(myString2)
? myString2 : "String 2 has nothing!");
}
}
}
Finally, below is the Main Method:
When I run this code, MyVariable returns null, I am assuming I am accessing the variable before it is assigned it's values?
How do I get the variable with the values assigned in the Method class?
namespace Classes
{
class Program
{
static void Main(string[] args)
{
MyMethods myMethod = new MyMethods();
MyVariableClass myVarClass = new MyVariableClass();
string something = "something";
string nothingHere = null;
myMethod.DoSomeStuff(something, nothingHere);
//I need to call MyVariable here
//Or be able to access it's values assigned in the MyMethod Class.
Console.Write(myVarClass.MyVariable);
Console.ReadKey();
}
}
}
Problem : You are working on two different objects.
you are creating an object with an instance variable myVarClass in MyMethods class.
you are creating one more new object with an instance variable myVarClass in Main() method.
Note : You should always remeber that in object oriented programming objects are independent and maintain their own copy so modifying one object parameters/properties doesnot effect the other object parameters or properties.
Solution : instead of creating two different object create only one object with instance variable myVarClass in Main() method and pass it to the myClass method.
so you should change your myClass method DoSomeStuff() as below to accept the instance variable of `MyVariableClass``
public void DoSomeStuff(MyVariableClass myVarClass, string myString1, string myString2)
{
//do something
}
from Main() method call the above method as below:
MyVariableClass myVarClass = new MyVariableClass();
string something = "something";
string nothingHere = null;
myMethod.DoSomeStuff(myVarClass, something, nothingHere);
Complete Code:
namespace Classes
{
class MyMethods
{
public void DoSomeStuff(MyVariableClass myVarClass, string myString1, string myString2)
{
myVarClass.MyVariable = (!string.IsNullOrEmpty(myString2)
? myString2 : "String 2 has nothing!");
}
}
}
and Main Program should be :
namespace Classes
{
class Program
{
static void Main(string[] args)
{
MyMethods myMethod = new MyMethods();
MyVariableClass myVarClass = new MyVariableClass();
string something = "something";
string nothingHere = null;
myMethod.DoSomeStuff(myVarClass, something, nothingHere);
//I need to call MyVariable here
//Or be able to access it's values assigned in the MyMethod Class.
Console.Write(myVarClass.MyVariable);
Console.ReadKey();
}
}
}
The myVarClass member of MyMethods is private by default, so if you want to be able to call it from outside the class itself, then you need to make it public.
Once public, you'll able to do:
static void Main(string[] args)
{
MyMethods myMethod = new MyMethods();
MyVariableClass myVarClass = new MyVariableClass();
string something = "something";
string nothingHere = null;
myMethod.DoSomeStuff(something, nothingHere);
//I need to call MyVariable here
//Or be able to access it's values assigned in the MyMethod Class.
Console.Write(myMethod.myVarClass.MyVariable);
Console.ReadKey();
}
Also, be careful with the fact that the myVarClass defined in main is a completely different object.
Cheers
Define you class as:
namespace Classes
{
class MyMethods
{
public MyVariableClass MyVarClass {get; private set;}
public void DoSomeStuff(string myString1, string myString2)
{
if(MyVarClass == null)
{
MyVarClass = new MyVariableClass();
}
MyVarClass.MyVariable = (!string.IsNullOrEmpty(myString2)
? myString2 : "String 2 has nothing!");
}
}
}
then use as:
namespace Classes
{
class Program
{
static void Main(string[] args)
{
MyMethods myMethod = new MyMethods();
string something = "something";
string nothingHere = null;
myMethod.DoSomeStuff(something, nothingHere);
//I need to call MyVariable here
//Or be able to access it's values assigned in the MyMethod Class.
Console.Write(myMethod.MyVarClass.MyVariable);
Console.ReadKey();
}
}
}
Say I have a class declared as follows:
public class ExampleClass
{
public Action<int> Do { get; set; }
public ExampleClass()
{
}
public void FuncA(int n)
{
//irrelevant code here
}
public void FuncB(int n)
{
//other irrelevant code here
}
}
I want to be able to use this class like this
ExampleClass excl = new ExampleClass() { Do = FuncA }
or
ExampleClass excl = new ExampleClass() { Do = excl.FuncA }
or
ExampleClass excl = new ExampleClass() { Do = ExampleClass.FuncA }
I can compile the second option there, but I get a "Delegate to an instance method cannot have null 'this'." exception when I hit that code. The third one doesn't even make sense, because FuncA isn't static.
In my actual code, there will be maybe 10-15 different functions it could get tied to, and I could be adding or removing them at any time, so I don't want to have to have a large switch or it-else statement. Additionally, being able assign a value to 'Do' when instantiating the class is very convenient.
Am I just using incorrect syntax? Is there a better way to create a class and assign an action in one line? Should I just man up and manage a huge switch statement?
You have to create the instance of the class and later set the property to the instance member. Something like:
ExampleClass excl = new ExampleClass();
excl.Do = excl.FuncA;
For your line:
ExampleClass excl = new ExampleClass() { Do = FuncA }
FuncA is not visible without an instance of the class.
For:
ExampleClass excl = new ExampleClass() { Do = excl.FuncA }
Instance has not yet been created that is why you are getting the exception for null reference.
For:
ExampleClass excl = new ExampleClass() { Do = ExampleClass.FuncA }
FuncA is not a static method, you can't access it with the class name.
In object initializer syntax you cannot access the variable being initialized before it is definitely assigned:
ExampleClass excl = new ExampleClass()
{
Do = excl.FuncA //excl is unavailable here
}
Read Object and Collection Initializers (C# Programming Guide) for more info.
You could do the following, for example:
public class ExampleClass
{
public Action<int> Do { get; set; }
public ExampleClass(bool useA)
{
if (useA)
Do = FuncA;
else
Do = FuncB;
}
public void FuncA(int n)
{
//irrelevant code here
}
public void FuncB(int n)
{
//other irrelevant code here
}
}
and use it:
ExampleClass exclA = new ExampleClass(true);
ExampleClass exclB = new ExampleClass(false);
Another idea is if these functions may be declared as static (i.e. they don't need any instance members of the ExampleClass), then this would work:
public class ExampleClass
{
public Action<int> Do { get; set; }
public ExampleClass() { }
public static void FuncA(int n) { /*...*/}
public static void FuncB(int n) { /*...*/}
}
and use it the way you want:
ExampleClass excl = new ExampleClass() { Do = ExampleClass.FuncA };
If you have extension methods make sure that those values are not null before invoking the extension methods or handle nulls inside the extension methods.
For example
public static ExtensionClass
{
public static bool RunExtensionMethod(this object myObject)
{
var someExecutionOnMyObject = myObject.IsValid();
//the above line would invoke the exception when myObject is null
return someExecutionOnMyObject ;
}
}
public void CallingMethod()
{
var myObject = getMyObject();
if(myObject.RunExtensionMethod()) //This would cause "delete to an instance method cannot have null" if myObject is null
{
}
}
To handle this scenario handle nulls and assert nulls if you own the extension class.
public static ExtensionClass
{
public static bool RunExtensionMethod(this object myObject)
{
if(myObject == null) throw new ArgumentNullException(nameof(myObject));
var someExecutionOnMyObject = myObject.IsValid();
return someExecutionOnMyObject ;
}
}
public void CallingMethod()
{
var myObject = getMyObject();
if(myObject != null && myObject.RunExtensionMethod())
{
}
}