Can I initialize an object with null?
I have an object Contact
, which is stored on disk.
Upon creating the contact object with Contact contact = new Contact("1234")
it is automatically beeing loaded from disk:
class Contact
{
public Contact(string id)
{
Node? testNode = NodeInterface.FileManager.LoadNode(id);
if (testNode != null)
{
LoadContact((Node) testNode);
}
else
{
throw new Exception("Contact does not exist on Disk!");
}
}
public string Name {get; set;}
public string Address {get; set;}
/* ... */
}
now I can initialize a Contact in the following ways:
Contact contact1 = new Contact("1234");
Contact nullContact1;
Contact nullContact2 = null;
Is it possible to replace the Line in the constructor which throws the Exception with something so that the Outcome is null?
Contact nullContact1 = new Contact("thisIdDoesNotExist");
Contact nullContact2 = null;
Calling new Contact
will always result in a Contact
object being created or an exception thrown. There's no way to cause a constructor to "return" null
.
You could, however, move this logic to another class and use the Factory design pattern:
public class ContactFactory
{
public static CreateContact(string id)
Node? testNode = NodeInterface.FileManager.LoadNode(id);
if (testNode != null)
{
return new Contact(testNode)
}
else
{
return null;
}
}
class Contact
{
public Contact(Node idNode)
{
LoadContact(idNode);
}
public string Name {get; set;}
public string Address {get; set;}
/* ... */
}