Tech Off Thread

5 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Get a name of derived class in c#

Back to Forum: Tech Off
  • User profile image
    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?

  • User profile image
    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).

  • User profile image
    alekseyfili​ppov

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

  • User profile image
    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.

  • User profile image
    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; }    }    }

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.