DotnetDude
DotnetDude

Reputation: 11807

Generic function Question C#

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;
}

Upvotes: 0

Views: 786

Answers (3)

Reed Copsey
Reed Copsey

Reputation: 564413

No, but this isn't really an appropriate use of generic methods in the first place. Just rewrite your method as:

protected virtual void LoadFieldDataEditor(Control control, BaseDataType objData, string strFieldName)
{
    SomeType1 type1 = objData as SomeType1;
    if (type1 != null)
    {
         // use type1.field1 here!
    }

}

Generic methods do nothing for you if you're constraining both types to two specific reference types. You can just use the base class directly - it's simpler, easier to call, more understandable, and works better overall.

Upvotes: 1

JaredPar
JaredPar

Reputation: 754725

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.

Upvotes: 3

Jim Arnold
Jim Arnold

Reputation: 2268

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

Upvotes: 1

Related Questions