basic c# problem

  • Thread starter Thread starter dot Net Pa Ji
  • Start date Start date
D

dot Net Pa Ji

Hi guys,
I work mostly with vb.net and today only started doping some C#. Can
some translate the following vb code in C#
'--Here conn is connection object
If Not (conn Is Nothing) Then
'-----
End If
 
If Not (conn Is Nothing) Then
'-----
End If
if (!(conn == null)){//so something
}

I would do it in VBNet as well as this bellow

If Not conn Is Nothing then
'do something
End if

Than it becomes more as Mark showed you.

I hope this helps,

Cor
 
null is the c# equivalent of VB Nothing

While that is true for reference types, Nothing is valid for value
types as well in VB. I *believe* that the default value for a member
variable of any particular type is the value of VB.NET's Nothing for
that same type - so for boolean it's false, for int it's 0 etc.

Not relevant in this particular example, but worth noting.

Jon
 
Hi Robinhood.

For your information in VB.Net is a difference between = Nothing and Is
Nothing.

= Nothing means for a value type empty or default
Is Nothing means for a reference type no reference.

By instance a string can have both

Setting to nothing is for both =

(Robin Hood because he came from Nothingham)

:-)

Cor
 
Thanks for the information.
---DNPJ
Cor Ligthert said:
Hi Robinhood.

For your information in VB.Net is a difference between = Nothing and Is
Nothing.

= Nothing means for a value type empty or default
Is Nothing means for a reference type no reference.

By instance a string can have both

Setting to nothing is for both =

(Robin Hood because he came from Nothingham)

:-)

Cor
 
Cor Ligthert said:
For your information in VB.Net is a difference between = Nothing and Is
Nothing.

= Nothing means for a value type empty or default
Is Nothing means for a reference type no reference.

By instance a string can have both

What makes a string different from other reference types though? That
doesn't make sense to me. Is it just to make it more like VB6?
 
What makes a string different from other reference types though? That
doesn't make sense to me. Is it just to make it more like VB6?

Pretty much. It's to make string compares work in a way similar to the
way they did in VB6. String comparisons are special-cased in VB.Net not
just for the reference/value type/empty means nothing/ issue, but
because VB also needs to support things like the Option Compare
statement, and there's some automatic culture stuff that's handled
during string compares (I doubt that one in a thousand VB developers
could tell you what String = String actually does in any detail.).

In VB.Net, for a string s

If s Is Nothing
works identically to if(s == null)

If s = Nothing

is equivalent to if(s == null || s == String.Empty)

Note this isn't polymorphic, you can't do

Dim s As Object = "Hello World"

If s = Nothing

That won't compile, because "= Nothing" is not valid for reference
types, except for Strings.
 
Back
Top