Runtime error when casting down type to another subtype

in many other types that I created, maybe a downCast type and I usually create an extension method, so it will be easier to control ...

BaseTypeM
BTDerV : BaseTypeM
BTDerLastDescndnt : BTDerV

now I create the type LastDerived and set its value to ParentType

BTDerV BTDer;

BTDerLastDescndnt BTDerLastDesc = new BTDerLastDescndnt(parA, ParB);


this.BTDer = BTDerLastDesc;

then using the downCast extension

var LDesc = this.BTDer.AsBTDerLastDescndnt();

which is actually

public static BTDerLastDescndnt AsBTDerLastDescndnt(this BTDerV SelfBTDerV )
{
    return (BTDerLastDescndnt)SelfBTDerV;
}

now when i do it as the code below, here it compiles but gives me a runtime error

        //BTDerV---v                 v---BaseTypeM
 public class SqlParDefV : SqlParameterM
 {
     public override SqlSpParDefMeta ParDMT
     {
         get { 
             return base.ParDMT;
         }
         set {
             base.ParDMT = value;
         }
     }
    public SqlParDefV(int bsprpOrdinal, string bsprpParName, MSSTypesS bdprpTypeS, bool bsprpIsDbStuctured, bool bsprpIsReq = true, ParameterDirection bsprpDirection = ParameterDirection.Input)
    {
        this.ParDMT = new SqlSpParDefMeta(bsprpOrdinal, bsprpParName, bdprpTypeS, bsprpIsReq, bsprpIsDbStuctured, bsprpDirection);
    }

}


       //BTDerLastDescndnt---v
public sealed class SqlParTvDrecDefinitionVScl : SqlParDefV
{
    public override SqlSpParDefMeta ParDMT
    {
        get {
            return base.ParDMT;
        }
        set {
            base.ParDMT = value;
        }
    }
    public SprocTvTargetSF.currentSDTObjType SqlObjType { get; set; }
    public SqlMetaData[] Meta { get; set; }

    public SqlParTvDrecDefinitionVScl(int bsprpOrdinal, string bsprpParName, SprocTvTargetSF.currentSDTObjType ctrSqlObjType, SqlMetaData[] parGeneratedSqlMetaData, MSSTypesS bdprpTypeS, bool bsprpIsDbStuctured, bool bsprpIsReq = true, ParameterDirection bsprpDirection = ParameterDirection.Input)
                        : base(bsprpOrdinal, bsprpParName, bdprpTypeS, bsprpIsDbStuctured, bsprpIsReq, bsprpDirection)
    {
        this.SqlObjType = ctrSqlObjType;
        this.Meta = parGeneratedSqlMetaData;
    }
}

Is there anything unusual here, or am I confused and missed some basic rule?

+4
source share
1 answer

, Derived MoreDerived. (: , ) as:

public static MoreDerived AsMoreDerived (this Derived d)
{
    return d as MoreDerived;
}

, as null, .

+2

Source: https://habr.com/ru/post/1622335/


All Articles