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.
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.
See more on this question at Stackoverflow