I am new to c# and use it with unity3D. When I use the new keyword to initialize an object it seems to have null in it even though the object is created and the constructor executes:
public class Wire
{
public Wire()
{
System.Console.WriteLine("constructor executed");
System.Console.WriteLine(this);
}
}
Wire wire1 =new Wire();
System.Console.WriteLine(wire1);
The output is:
constructor executed
null
null
I need to store the reference in a list but now I can’t. How can I solve this problem?
ok the actual code is
public class SharedResources
{
public static Dictionary< GameObject , Wire> dict =
new Dictionary<GameObject, Wire>();
//...
}
public class Wire
{
public GameObject x = y.y;
//y.y is another gameobject so its a normal copy constructer
public Wire()
{
print("constructor executed");
// print is provided from unity package
SharedResources.dict.Add( x,this);
}
}
and in the main i have
Wire wire1 = new Wire();
if ( SharedResources.dict.ContainsKey( wire1.x) )
{
print("ok"); // it does print that!!
if ( SharedResources.dict[wire1.x] !=null )
print("its not null");
else
print("its null");
}
output:
constructor executed
ok
its null
That is not possible.
The
thiskeyword can never be anullreference, a constructor can never return a null reference, and callingConsole.WriteLinewith a null reference doesn’t display “null”, it displays an empty line, i.e the same asConsole.WriteLine(String.Empty).You can get that behaviour if you override the
ToStringmethod to return the string"null":