Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property to set a type and return different type

I know that a property can be set as a single type and not to be changed once set, but is there a way to create a property or a property-like object that sets an int while returns a string?

I'm constantly creating variables like an int which will later on be used as string only and never to be used as int once set. So in that case i would always have to make a lot of conversions considering that it's not just one type to another.

like image 543
Explisam Avatar asked Oct 19 '22 06:10

Explisam


1 Answers

Maybe something like

struct strint 
{
   private int i; // 0 by default

   public static implicit operator strint(int value) {
       return new strint { i = value };
   }  

   public static implicit operator string(strint value) {
       return value.i.ToString();
   }

   public static implicit operator int(strint value) {
       return value.i;
   }
}

Sample use:

strint a = 1;
a += 2;         // 3
int i = a;      // 3
string s = a;   // "3"
like image 59
Slai Avatar answered Oct 21 '22 05:10

Slai