Reputation: 347
I'm working on a VB => C# translator, and I've run across some VB code that I'm not sure has a direct translation to C#.
In VB you can do something like
If {"a", "b", "c"}.Contains("c") Then ...
(and let's pretend it something useful that won't always be true)
What I'm wondering is if there is an equivalent of this in C#. The closest thing I can come up with is
if (new object[] {"a", "b", "c"}.Contains("c")) { ... }
My issue with this is that I have to define the type in C#, meaning I'd have to go with object - since I'm writing a translator, it would need to work equally well for an array of int
, array of bool
, array of custom classes, etc. I'm not sure that letting everything be an object instead of a more specific type is a good idea.
Is there a way to let the compiler figure out the type? Something logically like this: (I know this isn't ok, but something logically equivalent to ...)
if (new var[] {"a", "b", "c"}.Contains("c")) { ... }
so it treats the array as an array of strings and the Contains parameter as a string as well?
Side question: I'm under the impression that the VB code above treats {"a", "b", "c"}
as an array of string
. Is this correct? Does the VB code above treat "a", "b", and "c" as objects maybe - if so I'll use object in C# too.
Upvotes: 3
Views: 649
Reputation: 33576
Regarding side question:
fragment from 'Arrays in Visual Basic' on Microsoft Docs
Dim numbers = New Integer() {1, 2, 4, 8} Dim doubles = {1.5, 2, 9.9, 18}
When you use type inference, the type of the array is determined by the dominant type in the list of values that’s supplied for the array literal. The dominant type is a unique type to which all other types in the array literal can widen. If this unique type can’t be determined, the dominant type is the unique type to which all other types in the array can narrow. If neither of these unique types can be determined, the dominant type is
Object
. For example, if the list of values that’s supplied to the array literal contains values of typeInteger
,Long
, andDouble
, the resulting array is of typeDouble
. BothInteger
andLong
widen only toDouble
. Therefore,Double
is the dominant type. For more information, see Widening and Narrowing Conversions.
Upvotes: 0
Reputation: 1503924
If all the array elements will be the same type, or if they're different types but in a way that satifies type inference, you can use an implicitly typed array - like var
but for arrays, basically:
if (new[] { "a", "b", "b" }.Contains("c"))
I don't know whether that will be semantically the same as the VB code though.
Upvotes: 9