I have what I presume must be a common problem. Lets say I have a typical Person Class and I have a Car Class, which has a field/property owner of type Person:
public class Car
{
Person owner;
}
But sometimes I want the car to have no owner. What’s the recommended way of dealing with this problem. A Nullable type doesn’t work as reference types are already nullable.(Edit: clarification, I meant you cant use Person? owner;)
I could add in a bool field/property: hasOwner, but that seems rather verbose, so I thought of creating a static member none of type Person in the Person class like so:
namespace ConsoleApplication2
{
public class Person
{
public static Person none;
public int age;
static Person()
{
none = new Person();
}
}
public class Car
{
public Person owner;
}
class Program
{
static void Main(string[] args)
{
Car dumped = new Car();
dumped.owner = Person.none;
Console.ReadLine();
}
}
}
This compiles and runs, although I haven’t used it in a real application. Then I thought I could make a generic class with a none member as so:
namespace ConsoleApplication2
{
public class NoneMember<T> where T : new()
{
public static T none;
static NoneMember ()
{
none = new T();
}
}
public class Person: NoneMember<Person>
{
}
public class Car
{
public Person owner;
}
class Program
{
static void Main(string[] args)
{
Car dumped = new Car();
dumped.owner = Person.none;
if (dumped.owner == Person.none)
Console.Write("This car has no owner");
Console.ReadLine();
}
}
}
That compiles and runs, although there would be a problem if you wanted to inherit form the person class, with the generic and non generic versons. The thoughts of more experienced c# programmers would be appreciated.
Edit: The problem with using null to represent none is that you can’t pass null as a method / constructor parameter. null means value not set, which is different from value is none.
Edit2: I thought I was getting exceptions thrown when I passed null parameters. Not sure what was going on. I don’t know if I can reproduce the errors now.
I usually leave it as it is, if Car’s owner is null, that means just that – it does not have an owner. There is no need to complicate, if there is value – it has owner, otherwise it does not have (known to system) owner.
Exception from this policy is the case when you need to have journaling database, but in that case you usually can have versioned cars and owners and use the same principle.