Reputation: 2475
This is probably not possible, but I have this class:
public class Metadata<DataType> where DataType : struct
{
private DataType mDataType;
}
There's more to it, but let's keep it simple. The generic type (DataType) is limited to value types by the where statement. What I want to do is have a list of these Metadata objects of varying types (DataType). Such as:
List<Metadata> metadataObjects;
metadataObjects.Add(new Metadata<int>());
metadataObjects.Add(new Metadata<bool>());
metadataObjects.Add(new Metadata<double>());
Is this even possible?
Upvotes: 194
Views: 134530
Reputation: 117220
public abstract class Metadata
{
}
// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
private DataType mDataType;
}
Upvotes: 238
Reputation: 45445
I have also used a non-generic version, using the new
keyword:
public interface IMetadata
{
Type DataType { get; }
object Data { get; }
}
public interface IMetadata<TData> : IMetadata
{
new TData Data { get; }
}
Explicit interface implementation is used to allow both Data
members:
public class Metadata<TData> : IMetadata<TData>
{
public Metadata(TData data)
{
Data = data;
}
public Type DataType
{
get { return typeof(TData); }
}
object IMetadata.Data
{
get { return Data; }
}
public TData Data { get; private set; }
}
You could derive a version targeting value types:
public interface IValueTypeMetadata : IMetadata
{
}
public interface IValueTypeMetadata<TData> : IMetadata<TData>, IValueTypeMetadata where TData : struct
{
}
public class ValueTypeMetadata<TData> : Metadata<TData>, IValueTypeMetadata<TData> where TData : struct
{
public ValueTypeMetadata(TData data) : base(data)
{}
}
This can be extended to any kind of generic constraints.
Upvotes: 41
Reputation: 48265
Following leppie's answer, why not make MetaData
an interface:
public interface IMetaData { }
public class Metadata<DataType> : IMetaData where DataType : struct
{
private DataType mDataType;
}
Upvotes: 101