iif and type inference

M

Maurizio Colucci

Hello,

Is there a way in VB.NET to do something like

dim myInt = if foo() then bar(3) else 4

and have the compiler infer that myInt is an Integer, since bar()
returns an integer and 4 is an integer?

Thanks a lot for any info.

Maurizio
 
S

Stanimir Stoyanov

No, there is not a short equivalent of if-else in VB.NET as there is in C#
(condition ? true : false) but if you are sure that both statements return
an object of the same type, you can cast the result of IIf: CInt(IIf(foo(),
bar(3), 4)) in your case.

Best Regards,
Stanimir Stoyanov | www.stoyanoff.info
 
M

Martin H.

Hello Maurizio,

Since the code is not sooo difficult - why don't you just give it a try?

Best regards,

Martin
 
M

Maurizio Colucci

Hello Maurizio,

Since the code is not sooo difficult - why don't you just give it a try?

I'm sorry, I don't think I understand that you mean.

Maurizio
 
M

Maurizio Colucci

No, there is not a short equivalent of if-else in VB.NET as there is in C#
(condition ? true : false) but if you are sure that both statements return
an object of the same type, you can cast the result of IIf: CInt(IIf(foo(),
bar(3), 4)) in your case.

Thank you, I was afraid that was the only way. It also does not use
lazy evaluation.

Maurizio
 
N

Nick Hall

Stanimir Stoyanov said:
No, there is not a short equivalent of if-else in VB.NET as there is in C#
(condition ? true : false) but if you are sure that both statements return
an object of the same type, you can cast the result of IIf:
CInt(IIf(foo(), bar(3), 4)) in your case.

Note that if you're using VS 2008 this is no longer the case. The If
operator has been added which gives you type-safety and short circuiting
behaviour just like C#'s ? operator. Using the OP's example the code would
become: -

Dim myInt = If(foo(), bar(3), 4)

Also note that as this is a compiler feature you do not have to be
targetting the 3.5 version of the framework in order to use it.

Hope this helps,

Nick Hall
 
M

Maurizio Colucci

Which version ? If VB 2008, you could use the new If function :

        Dim myInt = If(foo(), bar(3), 4)

That's great! Exactly what I was hoping for. Thanks a lot Patrice.

M
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top