Tech Off Thread

5 posts

Get a name of derived class in c#

Back to Forum: Tech Off
  • alekseyfili​ppov

    Is it possible for each subclass of a parent class A to return its own class name as a property?

    There is a constraint in Couchbase .NET client for models to expose a class-name property. As it is reflected in their documentation it can be resolved by using this code:

    class abstract BaseModel {
        public abstract String Type {get;}
    }
    
    class Robot : BaseModel {
        public override String Type {
            get { return "Robot"; }
        }
    }
    

    Is it possible to automate this from within the BaseModel class?

  • wkempf

    this.GetType().Name

    That said, I'd be very curious why Couchbase has this requirement, because they could do the same thing externally, which would be safer (classes can't lie).

  • alekseyfili​ppov

    @wkempf:Did you mean internally? Yes, it is strange thing. Thank you!

  • wkempf

    No, I meant externally. They currently consume model.Type externally, which you have to implement to return a string. Instead, they could consume model.GetType().Name externally, which would mean you wouldn't have to implement the Type property.

  • PopeDai

    , alekseyfili​ppov wrote

    Is it possible for each subclass of a parent class A to return its own class name as a property?

    There is a constraint in Couchbase .NET client for models to expose a class-name property. As it is reflected in their documentation it can be resolved by using this code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    class abstract BaseModel {
        public abstract String Type {get;}
    }
     
    class Robot : BaseModel {
        public override String Type {
            get { return "Robot"; }
        }
    }

    Is it possible to automate this from within the BaseModel class?

    abstract class BaseModel {        public virtual String Type {        get { return this.GetType().Name; }    }    }

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.