If you simply designed your class like this:
public abstract class Bundled<T>
{
private Tuple<T, object> _bundle;
public T Value
{
get { return _bundle == null ? default(T) : _bundle.Item1; }
set { _bundle = new Tuple<T, object>(value, internalObj); }
}
}
Then you can use it with a struct by specifying the type parameter as a Nullable<T>
, for example:
Bundled<string> foo; // handles classes
Bundled<float?> bar; // handles structs
The only problem here is that it's possible that a user could use this class with a non-nullable struct—e.g. Bundled<int>
. If that's really a concern in your application, you could declare more specific sub-types like this:
public class BundledClass<T> : Bundled<T> where T : class { }
public class BundledStruct<T> : Bundled<T?> where T : struct { }
You also can make the constructor for Bundled<T>
internal so it can't be called from outside your assembly. This will ensure that the user doesn't create a custom sub-type to bypass your BundledClass
/ BundledStruct
wrappers.