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
Related
Say you had some sort of console-application game, and inside the game you create an object which would have it's own class. How would you make an instance of that class with something like a method or function while the game might still be running.
I've looked all over the internet and haven't found anything after weeks. Normally, I would just create an array for the class and add new instances to it like so.
class MyClass
{
//fields and methods
}
class Program
{
static void Main(string[] args)
{
MyClass[] myClasses = new MyClass[16];
myClasses.SetValue(new MyClass(), 0);
}
}
But this feels clunky and inefficient. I hope I figure this out soon.
There are many ways to do this. The most common and accepted way may be the FactoryPattern.
Create your factory:
public static class MyClassFactory
{
public static MyClass CreateNew() {
return new MyClass();
}
public static MyClass[] CreateRange(int amount) {
var myArr = new MyClass[amount];
for (int i = 0; i < amount; i++)
{
myArr[i] = new MyClass();
}
return myArr;
}
}
Then simply call it in your code:
class Program
{
static void Main(string[] args)
{
MyClass[] myClasses = MyClassFactory.CreateRange(16);
}
}
Are you trying to do this:
var myClasses = new MyClass[16];
myClasses[0] = new MyClass();
In my application I need to have few singleton classes. Each of them has some fields of others singleton classes to use them. Below I reconstructed the issue on simple example:
public sealed class A
{
private B b = B.Instance;
private static readonly A instance = new A();
public static A Instance { get { return instance; } }
static A() { }
private A() { }
public void Do()
{
b.ToString();
}
}
public sealed class B
{
A a = A.Instance;
private static readonly B instance = new B();
public static B Instance { get { return instance; } }
static B() { }
private B() { }
public void Do()
{
a.ToString();
}
}
class Program
{
static B b = B.Instance;
static A a = A.Instance;
static void Main(string[] args)
{
b.Do();
a.Do();
}
}
Null reference exception coming because fields are null. So how can I initialize and use such interconnected singleton classes?
The constructors don't run in parallel so when the first is being created the second Singleton has not yet been created.
Instead of setting the property to the value directly you'd likely write something like this in class B:
private A AProp {
get {
if(a == null)
a = A.Instance;
return a;
}
}
You'd do the same the other way round in class A. So getting the value is delayed until first access and at that time the other Singleton has already been created.
In what scenario exactlly something like this is a good idea is another question. Especially given that instead of accessing it in a local field you could always just access it using A.Instance anyway (so the local field becomes kind of redundant at that point.
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);
}
}
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())
{
}
}
As far as I understand the concept of delegates, they simply point to a method. Then when I'm feeling lucky I can go out and invoke the method my delegate is pointing to, right?
Given is the following code:
class Program
{
static void Main(string[] args)
{
Func<MyClass> myAct = GetAct();
Method(myAct);
}
private static Func<MyClass> GetAct()
{
MyClass obj = new MyClass()
{
Prop1 = 5
};
Func<MyClass> myAct = new Func<MyClass>(
() =>
{
MyClass obj2 = new MyClass();
MyClass2 obj3 = new MyClass2()
{
Prop3 = 25,
Prop4 = "test"
};
obj2.Prop2 = ((obj.Prop1 + 5) * obj3.Prop3)
.ToString() + obj3.Prop4;
return obj2;
});
return myAct;
}
static void Method(Delegate func)
{
GC.Collect();
GC.WaitForPendingFinalizers();
var result = func.DynamicInvoke();
}
}
class MyClass
{
public int Prop1 { get; set; }
public string Prop2 { get; set; }
}
class MyClass2
{
public int Prop3 { get; set; }
public string Prop4 { get; set; }
}
Now my delegate myAct (in this case a Func<MyClass>) is pointing to an anonymous function which performs some simple assignation of variables. Nothing special so far.
We invoke the delegate.
Everything went fine, just as we expected. But the question is why? If the delegate just simply points to the anonymous method AND a garbage collection was done, how could the CLR know what obj and it's values are?
Where is the reference to obj stored, to be available when the function is called? Inside the delegate?
Your anonymous method is defined within the scope of GetAct() so CLR makes scope variables available to the anonymous method.
It's similar to how an instance variable is usable by member methods.
Also, review the pitfalls of using closures: http://msmvps.com/blogs/peterritchie/archive/2010/11/03/deep-dive-on-closure-pitfals.aspx