views:

358

answers:

3

I have a generic function and the following class hiearchy:

protected virtual void LoadFieldDataEditor <T1, T2> (T1 control, T2 objData, string strFieldName) where T1 : Control where T2 : BaseDataType
{
  //I will need to access field1. 
  //I don't know at compile time if this would be SomeType1 or 
 //SomeType2 but all of them inherit from BaseDataType. 

  //Is this possible using generics?
}

public abstract class BaseDataType {}

public class SomeType1 : BaseDataType
{
   string field1;
   string field2;
}

public class SomeType2 : BaseDataType
{
   string field3;
   string field4;
}
+1  A: 

No. Unless "field1" is declared on BaseDataType, it will not be accessible without casting to SomeType1.

Jim Arnold
+3  A: 

This is only possible if you have some concrete type which exposes field1. In this case you have BaseDataType which can given a virtual property that is implemented in all base classes.

public abstract class BaseDataType {
  public abstract string Field1 { get; } 
}

This allows you to access the property within LoadFieldDataEditor

protected virtual void LoadFieldDataEditor <T1, T2> (T1 control, T2 objData, string strFieldName) where T1 : Control where T2 : BaseDataType
{
  string f1 = objData.Field;
}

Implementing the property in SomeType1 is straight forward. Simply implement the property and return the underlying field.

public class SomeType1 : BaseDataType {
  public override string Field1 { get { return field1; } }
  // Rest of SomeType
}

The question though is what should SomeType2 return for Field1? It's unclear by your question how this should be implemented.

JaredPar
+1  A: 
Reed Copsey