Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make this parameter access syntax possible?

Tags:

c#

public class SampleClass {
     public int value;

     public SampleClass(int v)
     { value = v; }
}

// i want to access value like this
SampleClass sc = new SampleClass(5);

int i = sc;

Is there a way to do this in C#? I don't want to have to say sc.Value every time i need to access the value.

like image 459
Behrooz Karjoo Avatar asked Mar 10 '11 20:03

Behrooz Karjoo


1 Answers

Use an implicit conversion:

public class SampleClass {
     public int value;

     public SampleClass(int v)
     { value = v; }

     public static implicit operator int (SampleClass c)
     {
       return c.value;
     }
}

You should look into properties however.

like image 148
Femaref Avatar answered Sep 27 '22 19:09

Femaref