(byte)0 - What exactly does this syntax mean?

M

Mike

Hi. I'm a VB.NET guy trying my best to learn C#.NET. I have an existing C#
application I'm trying to understand, and there is one piece of syntax I
can't wrap my head around. It is:

(byte)0

What exactly does this mean in C#? I can't find a VB.NET equivelent.

If someone could help me out I'd appreciate it.

Thanks!
 
P

parez

Hi. I'm a VB.NET guy trying my best to learn C#.NET. I have an existing C#
application I'm trying to understand, and there is one piece of syntax I
can't wrap my head around. It is:

(byte)0

What exactly does this mean in C#? I can't find a VB.NET equivelent.

If someone could help me out I'd appreciate it.

Thanks!

CType(0, Byte)
i think you would need that in vb.net only if have
Option Strict On
 
L

Lenn

The line of code you provided casts type int to byte. Generally the way you
type cast in c# is:

DataTypeY variableY = (DataTypeY)variableX;

The VB equivelant would be:

Dim x as DataTypeX

y = CType(x, DataTypeY)

It's been a while since I did any VB.NET, so I could be off. Google VB.NET
CType function.
 
M

Mike

That explains it - Thanks!!

Lenn said:
The line of code you provided casts type int to byte. Generally the way you
type cast in c# is:

DataTypeY variableY = (DataTypeY)variableX;

The VB equivelant would be:

Dim x as DataTypeX

y = CType(x, DataTypeY)

It's been a while since I did any VB.NET, so I could be off. Google VB.NET
CType function.
 
J

Jon Skeet [C# MVP]

Peter Duniho said:
Where do you see that?

The other replies are basically correct, but...0 (and any other int within
0 to 255) is implicitly convertable to byte. It shouldn't be necessary to
cast the literal 0 to byte.

The exception being when you want to use a byte overload instead of an
int overload, of course:

using System;

public class Test
{
static void Main()
{
Foo(0);
Foo((byte)0);
}

static void Foo(int i)
{
Console.WriteLine("int");
}

static void Foo(byte i)
{
Console.WriteLine("byte");
}
}
 
H

Hilton

Jon,

Good point. Here's an interesting one too (well, I found it interesting
although I'm sure it is documented somewhere):

using System;

public class Test
{
static void Main()
{
Foo(0);
}

static void Foo(float x)
{
Console.WriteLine("float");
}

static void Foo(double x)
{
Console.WriteLine("double");
}
}
 
J

Jon Skeet [C# MVP]

Good point. Here's an interesting one too (well, I found it interesting
although I'm sure it is documented somewhere):

It's in the spec in section 7.4.3.4 (C# 3.0 spec). There's an implicit
conversion from int to float, int to double, and float to double.

The last of these means that the conversion from int to float is
"better than" the conversion from int to double.

Jon
 

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