I have a class Data<T>
which I use to store data received on a communication link. The Data<T>
class contains a Value
property of type T
and a Timestamp
property of type DateTime
.
Is it possible to determine in the class constructor that the requested type's default value is null
, and in that case instantiate it?
I've looked at the new()
class constraint. But then I'm having trouble using the class with a string type, as I'm getting errors about string not having a parameterless constructor.
Here's an example causing a NullReferenceException on dataValue4.Value
, since the Value
property of type Foo
is not instantiated.
public class Data<T> {
public Data() {
_timestamp = DateTime.Now;
}
private T _value;
public T Value {
get { return _value; }
set {
_value = value;
_timestamp = DateTime.Now;
}
}
private DateTime _timestamp;
public DateTime Timestamp {
get { return _timestamp; }
}
}
public class Foo {
public int Value1 { get; set; }
public bool Value2 { get; set; }
}
public class Program {
public static void Main() {
var dataValue1 = new Data<int>();
var dataValue2 = new Data<bool>();
var dataValue3 = new Data<string>();
var dataValue4 = new Data<Foo>();
//dataValue4.Value = new Foo();
Console.WriteLine(dataValue1.Value); // Output is "0"
Console.WriteLine(dataValue2.Value); // Output is "False"
Console.WriteLine(dataValue3.Value); // Output is ""
Console.WriteLine(dataValue4.Value.Value1); // Output is "0"
Console.WriteLine(dataValue4.Value.Value2); // Output is "False"
}
}