Home > Net >  Detect nested type of generic
Detect nested type of generic

Time:11-12

I'm working on a project which needs to determine the type of an object, take the information from that type and move it to a structure that fits in our database.

For this, I'm using Pattern Matching with a case statement which works fine.

The only thing that I got stuck with is that some types have nested types as well. The information in those nested types is the information that I need.

Take a look at the code below:

    public class CallAnswered
    {
        public string Caller { get; set; }
        public MetaDataInformation MetaData{ get; set; }
    }

    public class CallAbandoned
    {
        public string ReasonForAbandonment{ get; set; }
        public MetaDataInformation MetaData { get; set; }
    }

    public class MetaDataInformation 
    {
        public DateTime ReceivedAt { get; set; }
        public DateTime AnsweredAt { get; set; }
    }

    public void DetermineType<T>(T callEvent)
    {
        switch (callEvent)
        {
            case CallAnswered callAnswered:
            case CallAbandoned callAbandoned:

            // Somehow, I need to access the "MetaData" property as a type
            break;
        }
    }

Like shown in the code above, I am able to detect the parent type and assign it a variable. Bu I have no clue on how to get the nested MetaDataInformation type.

Does anyone have an idea how this can be resolved?

CodePudding user response:

You do not need a generic type here. By deriving from an abstract base class, you can solve two problems.

  1. You can use the base type instead of the generic type and access all the public members of this base class.
  2. You can add an abstract method in the base class implemented in the two derived classes making the switch statement obsolete.
public abstract class Call
{
    public MetaDataInformation MetaData { get; set; }
    public abstract void Process();
}

public class CallAnswered : Call
{
    public string Caller { get; set; }

    public override void Process()
    {
        // TODO: Do Answer things. You can access MetaData here.
    }
}

public class CallAbandoned : Call
{
    public string ReasonForAbandonment{ get; set; }

    public override void Process()
    {
        // TODO: Do Abandonment things. You can access MetaData here.
    }
}

somewhere else

public void ProcessCalls(Call callEvent)
{
    // Replaces switch statement and does the right thing for both types of calls:
    callEvent.Process();
}

This is called a polymorphic behavior.

See also:

  • Related