C # equivalent to {}. States () in VB

I am working on a VB => C # translator and I came across some VB code that I am not sure has a direct translation to C #.

In VB, you can do something like

If {"a", "b", "c"}.Contains("c") Then ...

      

(and let him pretend to be useful, which will not always be true)

I'm wondering if there is an equivalent to this in C #. The closest I can think of is

if (new object[] {"a", "b", "c"}.Contains("c")) { ... }

      

My problem is that I have to define the type in C #, that is, I have to go with an object - since I am writing a translator, it should work equally well for an array int

, an array from bool

, an array of custom classes, etc. I'm not sure if letting everything be an object instead of a more specific type is a good idea.

Is there a way to make the compiler understand the type? Something logically like this: (I know this is not ok, but something is logically equivalent ...)

if (new var[] {"a", "b", "c"}.Contains("c")) { ... }

      

so it treats the array as an array of strings and the Contains parameter is also a string?

Side question: I am under the impression that the VB code above is treating {"a", "b", "c"}

as an array string

. It's right? Does the VB code above highlight "a", "b" and "c" as objects, perhaps if I use an object in C # too.

+3


source to share


2 answers


If all the elements of an array will be of the same type, or if they are different types, but in a way that suits the output type, you can use an implicitly typed array - for example var

, but for arrays, basically:

if (new[] { "a", "b", "b" }.Contains("c"))

      



I don't know if the semantics will be the same as the VB code.

+9


source


Regarding the side question:

snippet from "Arrays in Visual Basic" in Microsoft Docs



Dim numbers = New Integer() {1, 2, 4, 8}
Dim doubles = {1.5, 2, 9.9, 18}

      

When using type inference, the type of the array is determined by the dominant type in the list of values ​​that were supplied for the array literal. A dominant type is a unique type that all other types in a literal array are extensible to. If this unique type cannot be determined, the dominant type is the unique type, to which all other types in the array can be narrowed down. If none of these unique types can be determined, the dominant type is Object

. For example, if the list of values ​​that are passed to an array literal contains values ​​of type Integer

, Long

and Double

, the resulting array is of type Double

. Both Integer

and Long

extend only to Double

. Hence,Double

is the dominant type. For more information, see Expanding and Narrowing Conversions .

0


source







All Articles