-1

I previously worked on a C# project but now I'm working with Visual Basic and what I want to do is simply translate the C# code to Visual Basic and it's going fine except for one piece of code of C# that I have no idea how to translate to VB

The C# code is:

private void ReadInput(Animal animal)
{
    // Mammal is a class that inherits from the Animal class
    Mammal mammal = animal as Mammal; //<<----How to translate this code?
    if (mammal != null)
    {
        mammal.Teeth = ReadTeeth();
    }
}

I'm not really sure how to translate animal as Mammal to Visual Basic.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
John.P
  • 657
  • 2
  • 9
  • 22

2 Answers2

3

Use TryCast to treat animal as mammal

 Dim mammal As Mammal = TryCast(animal, Mammal) 
Blackwood
  • 4,504
  • 16
  • 32
  • 41
1

The missing piece in your conversion is TryCast(animal, Mammal)


There are a lot of code converters online that can help you to answer questions of the type "how can I translate code x from language y to language z?":

and more ...

Note: Some converters only work properly if you embed your code snippet into a class. For your specific example, some of them had trouble with the code comments. After removing them, everything went smooth.

They will yield something like this (comments removed):

Private Sub ReadInput(animal As Animal)
    Dim mammal As Mammal = TryCast(animal, Mammal)
    If mammal IsNot Nothing Then
        mammal.Teeth = ReadTeeth()
    End If
End Sub
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188