return default ToString() for a class instance c# -


i have class named person

public class person     {        string name;       int age;       sampleobject(string name, int age)       {       this.name = name;       this.age = age;       }       public override string tostring()        {          string s = age.tostring();          return "person: " + name + " " + s;       }     } 

i have overridden tostring() return name of person.

i using class in class:

public class myclass {  public int id {get;set;}  public person person {get;set;}  } 

now, want access class as

myclass = new myclass(); 

i want when execute my.person, should return tostring() value of person class without explicitly calling my.person.tostring()

is possible , if possible, how can make happen.

thanks

i don't understand question well. 1 of solutions question use implicit cast.

    public class person     {         string name;         int age;         public person(string name, int age)         {             this.name = name;             this.age = age;         }         public override string tostring()         {             string s = age.tostring();             return "person: " + name + " " + s;         }         // here         public static implicit operator string(person d)         {             return d.tostring();         }     }     public class myclass     {          public int id { get; set; }          public person person { get; set; }      }     static void main(string[] args)     {         var myclass = new myclass();         myclass.person = new person("test", 12);         // use         string name = myclass.person;         console.writeline(name);         console.writeline("press key continue.");         console.readline();     } 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

Kivy: Swiping (Carousel & ScreenManager) -

jdbc - Not able to establish database connection in eclipse -