I've written a simple abstract generic class in C# (.NET 2.0) and I preferably want to limit it to only reference types, so I can indicate no value by a null. However, I also want to use types such as long and decimal, why don't allow null (being structs after all). I considered making the class
public abstract Field<Nullable<T>>
{
}
But that would prevent my use of the string type, which is a class. How can I box up my decimals and longs so I can use them in this generic.
abstract class Field<T>
{
private int _Length = 1;
private bool _Required = false;
protected T _Value; //= null;
public int Length
{
get { return _Length; }
private set
{
if (value < 1) throw new ArgumentException("Field length must be at least one.");
_Length = value;
}
}
public bool Required
{
get { return _Required; }
private set { _Required = value; }
}
public abstract string GetFieldValue();
public abstract void ParseFieldValue(string s);
public virtual T Value
{
get { return _Value; }
set
{
if (value == null && Required)
throw new ArgumentException("Required values cannot be null.");
_Value = value;
}
}
}
Please note that I need to represent numeric 0 and null differently. For this reason default(T) will not work.