Search code examples
c#generics.net-2.0struct

What types to use for boxing in generics


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.


Solution

  • You would need two classes

    abstract class FieldR<T> where T: class
    {
      T Value { get {} set {} }
    }
    
    abstract class FieldV<T> where T: struct
    {
      Nullable<T> Value { get {} set {} }
    }
    

    The first class would use

    T
    

    While the second class would use

    Nullable<T>