Doubt about classes c #

1

I have two class is a call Autos and another Utilitarios . When I go to look for a vehicle for its registration in Autos and that registration belongs to a Utilitario I skip error in the code below. How can I, instead of having an error, I throw a message saying that this vehicle belongs to the class Utilitario .

else {
      Console.WriteLine(((Utilitarios)v).MostrarPolimorfico());
      Console.WriteLine("\n" + "¿Que desea hacer?");
      Console.WriteLine("\n" + "1- EDITAR INFORMACION");
      Console.WriteLine("2- BORRAR VEHICULO");
    
asked by Francop 20.07.2017 в 02:14
source

2 answers

2

Although obviously try/catch can solve the problem, it is not advisable to use the exceptions to manage this type of errors. In this case, a simple check of the type of the instance using is enough and the code is more readable and clean:

else {
  if (v is Utilitarios)
  {
      Console.WriteLine(((Utilitarios)v).MostrarPolimorfico());
      Console.WriteLine("\n" + "¿Que desea hacer?");
      Console.WriteLine("\n" + "1- EDITAR INFORMACION");
      Console.WriteLine("2- BORRAR VEHICULO");
  }
  else
  { 
      Console.WriteLine("El vehiculo no es un utilitario");
  }
    
answered by 20.07.2017 / 09:10
source
3

In order to capture an error and personalize the message you must put your code inside a Try Catch.

class MyClass 
{
   public static void Main() 
   {
      MyClass x = new MyClass();
      try 
      {
         string s = null;
         x.MyFn(s);
      }

      catch (Exception e)
      {
         Console.WriteLine("{0} Exception caught.", e);
      }
   }

Check this link Try Catch

    
answered by 20.07.2017 в 03:50