How can you use parameter access syntax?

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 any way to do this in C #? I don't want to tell sc.Value every time I need to access a value.

+6
c #
source share
4 answers

Use implicit conversion:

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

However, you should study the properties .

+10
source share

You can do this by enabling implicit conversion from SampleClass to int:

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

... but I would strongly recommend that you not do this, or at least that you think very carefully in advance. Implicit conversions make it difficult to reason about a language in various ways (for example, consider things like, for example, resolving overloads).

Very, very sometimes it is recommended to introduce implicit conversions - for example, LINQ to XML makes excellent use of it with a string in XNamespace and a string in XName conversions, but I would not do this here just to avoid using .Value .

It’s a little more reasonable to make an explicit conversion (just change the implicit to explicit in the conversion of the statement) so that at least it makes it clear what happens in the calling code ... but at the same time, in reality, there is a difference between the original size between cast to int and using .Value is small.

(And, as suggested elsewhere, do not make the fields public - use properties instead.)

+2
source share

Take a look at this . You need to overload the implicit translation operator for int.

+1
source share

Yes it is possible. You need to implement the implicit for your SampleClass: Here it is:

 public class SampleClass { public int Value; public SampleClass(int v) { Value = v; } public static implicit operator int(SampleClass d) { return d.Value; } } 
0
source share

All Articles