Is Generic type and getting its value

I’ve got a simple class I use in a framework so the business objects can use different distinct identifiers (DB int, guid, key etc).

public class Identifier<t>
{
	private T _value;
	public Identifier(){
 
	}
	public Identifier(T value)
	{
		Value = value;
	}
	public T Value
	{
		get { return _value; }
		set { _value = value; }
	}
	/* implicit conversions */
	public static implicit operator int(Identifier</t><t> d)
	{
		return (int)(object)d.Value;
	}
}</t>

I have implicit and explicit operators so that the follwing works:

Identifier<int> GenericId = new Identifier<T>();
//the cast is implicit so no need to use GenericId.Value
Int32 id = GenericId;

I needed to pass identifiers as Object to the add db params method. Took me a while to figure out but this how to check if an object is a generic type and get the value of one of it’s properties

private object GetValue(object value)
{
  Type t = value.GetType();
  if (t.IsGenericType)
  {
    if (t.GetGenericTypeDefinition() == typeof(Identifier<>)) //check the object is our type
    { 
      //Get the property value
      return t.GetProperty("Value").GetValue(value, null);
    }
  }
  return value;
}

Leave a Reply

Your email address will not be published. Required fields are marked *