Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. Is their a better way than using the Try/Catch statement in this source?

Is their a better way than using the Try/Catch statement in this source?

Scheduled Pinned Locked Moved C#
tutorialquestion
6 Posts 3 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • V Offline
    V Offline
    venomation
    wrote on last edited by
    #1

    Hey I am a college student and recently figured out how to down/up cast types and get derived values form them. I made a simply (certainly not elegant) experimental program for it but I dont want to use Try/Catch in the "ShowDetails" method. There must be a better way than this !

    class Program
    {
    static List<IProduct> productList = new List<IProduct>();
    static void Main(string[] args)
    {
    Console.WriteLine("What product would you like to purchase");
    Console.WriteLine("1 Xbox");
    Console.WriteLine("2 Ps3");
    Console.Write("Number: ");
    char choice = Console.ReadLine()[0];
    Choice ch = Makedescision(choice);
    EvaluateDescision(ch);
    Console.ReadKey();
    }
    enum Choice { xbox = 1, ps3 = 2, nothing };

        static Choice Makedescision(char input)
        {
            if (input.Equals('1'))
            {
                return Choice.xbox;
            }
            else if (input.Equals('2'))
            {
                return Choice.ps3;
            }
    
            return Choice.nothing;
    
        }
        static void EvaluateDescision(Choice ch)
        {
            if (ch == Choice.xbox)
            {
                MakeNewXbox();
            }
            else if (ch == Choice.ps3)
            {
                MakeNewPs3();
            }
        }
    
        static void MakeNewXbox()
        {
            Xbox product = new Xbox();
            Console.WriteLine("Name your xbox");
            product.Name = Console.ReadLine();
            product.quantity = 2;
            product.Cost = 129.99m;
            productList.Add(product);
            ShowDetail(0);
    
        }
        static void MakeNewPs3()
        {
            Ps3 product = new Ps3();
            Console.WriteLine("Is new?");
            bool isNew = bool.Parse(Console.ReadLine());
            product.IsNew = isNew;
            product.Cost = 129.99m;
            productList.Add(product);
            ShowDetail(0);
    
        }
    
        static void ShowDetail(int i)
        {
            int quantity;
            bool detail;
            IProduct prod = (IProduct)productList\[i\];
            try
            {
                quantity = ((Xbox)(prod)).quantity;
                Console.WriteLine("quantity is " + quantity);
                
            }catch(Exception e)
            {
            }
            try
            {
    
    OriginalGriffO 1 Reply Last reply
    0
    • V venomation

      Hey I am a college student and recently figured out how to down/up cast types and get derived values form them. I made a simply (certainly not elegant) experimental program for it but I dont want to use Try/Catch in the "ShowDetails" method. There must be a better way than this !

      class Program
      {
      static List<IProduct> productList = new List<IProduct>();
      static void Main(string[] args)
      {
      Console.WriteLine("What product would you like to purchase");
      Console.WriteLine("1 Xbox");
      Console.WriteLine("2 Ps3");
      Console.Write("Number: ");
      char choice = Console.ReadLine()[0];
      Choice ch = Makedescision(choice);
      EvaluateDescision(ch);
      Console.ReadKey();
      }
      enum Choice { xbox = 1, ps3 = 2, nothing };

          static Choice Makedescision(char input)
          {
              if (input.Equals('1'))
              {
                  return Choice.xbox;
              }
              else if (input.Equals('2'))
              {
                  return Choice.ps3;
              }
      
              return Choice.nothing;
      
          }
          static void EvaluateDescision(Choice ch)
          {
              if (ch == Choice.xbox)
              {
                  MakeNewXbox();
              }
              else if (ch == Choice.ps3)
              {
                  MakeNewPs3();
              }
          }
      
          static void MakeNewXbox()
          {
              Xbox product = new Xbox();
              Console.WriteLine("Name your xbox");
              product.Name = Console.ReadLine();
              product.quantity = 2;
              product.Cost = 129.99m;
              productList.Add(product);
              ShowDetail(0);
      
          }
          static void MakeNewPs3()
          {
              Ps3 product = new Ps3();
              Console.WriteLine("Is new?");
              bool isNew = bool.Parse(Console.ReadLine());
              product.IsNew = isNew;
              product.Cost = 129.99m;
              productList.Add(product);
              ShowDetail(0);
      
          }
      
          static void ShowDetail(int i)
          {
              int quantity;
              bool detail;
              IProduct prod = (IProduct)productList\[i\];
              try
              {
                  quantity = ((Xbox)(prod)).quantity;
                  Console.WriteLine("quantity is " + quantity);
                  
              }catch(Exception e)
              {
              }
              try
              {
      
      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #2

      Try doing a safe cast:

      Xbox xb = prod as Xbox;
      if (xb != null)
      {
      ...
      }

      You could also use

      if (prod is Xbox)
      {
      ...
      }

      but the "as" cast will cope with nulls better. [edit]Oops! put the <pre> tag in teh wrong place - fixed[/edit]

      No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones "Rumour has it that if you play Microsoft CDs backwards you will hear Satanic messages.Worse still, is that if you play them forwards they will install Windows"

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      V V 2 Replies Last reply
      0
      • OriginalGriffO OriginalGriff

        Try doing a safe cast:

        Xbox xb = prod as Xbox;
        if (xb != null)
        {
        ...
        }

        You could also use

        if (prod is Xbox)
        {
        ...
        }

        but the "as" cast will cope with nulls better. [edit]Oops! put the <pre> tag in teh wrong place - fixed[/edit]

        No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones "Rumour has it that if you play Microsoft CDs backwards you will hear Satanic messages.Worse still, is that if you play them forwards they will install Windows"

        V Offline
        V Offline
        venomation
        wrote on last edited by
        #3

        Awesome works very well, surprisingly i have came across this "as" syntax before and surprised i didnt think about it xD Thanks :)

        OriginalGriffO 1 Reply Last reply
        0
        • OriginalGriffO OriginalGriff

          Try doing a safe cast:

          Xbox xb = prod as Xbox;
          if (xb != null)
          {
          ...
          }

          You could also use

          if (prod is Xbox)
          {
          ...
          }

          but the "as" cast will cope with nulls better. [edit]Oops! put the <pre> tag in teh wrong place - fixed[/edit]

          No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones "Rumour has it that if you play Microsoft CDs backwards you will hear Satanic messages.Worse still, is that if you play them forwards they will install Windows"

          V Offline
          V Offline
          vtchris peterson
          wrote on last edited by
          #4

          Agreed that type-safe casting is far superior to blanket try/catch in the original code. As for "as" vs. "is"... As far as I know, "as" and "is" both cope with nulls the same way, "as", however has an advantage when you need to use the instance through the casted type, i.e. you wouldn't want to do an "is" check only to then do an "as" cast after the fact. In any event, you should consider exposing functionality common to both product types through the IProduct interface. Inheritence is only a useful design pattern when common functionality exists at certain levels of the type heirarchy -- if you constantly have to up and down cast, you're probably forcing a flawed design.

          V 1 Reply Last reply
          0
          • V venomation

            Awesome works very well, surprisingly i have came across this "as" syntax before and surprised i didnt think about it xD Thanks :)

            OriginalGriffO Offline
            OriginalGriffO Offline
            OriginalGriff
            wrote on last edited by
            #5

            You're welcome.

            No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones "Rumour has it that if you play Microsoft CDs backwards you will hear Satanic messages.Worse still, is that if you play them forwards they will install Windows"

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
            "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

            1 Reply Last reply
            0
            • V vtchris peterson

              Agreed that type-safe casting is far superior to blanket try/catch in the original code. As for "as" vs. "is"... As far as I know, "as" and "is" both cope with nulls the same way, "as", however has an advantage when you need to use the instance through the casted type, i.e. you wouldn't want to do an "is" check only to then do an "as" cast after the fact. In any event, you should consider exposing functionality common to both product types through the IProduct interface. Inheritence is only a useful design pattern when common functionality exists at certain levels of the type heirarchy -- if you constantly have to up and down cast, you're probably forcing a flawed design.

              V Offline
              V Offline
              venomation
              wrote on last edited by
              #6

              vtpdawg wrote:

              any event, you should consider exposing functionality common to both product types through the IProduct interface. Inheritence is only a useful design pattern when common functionality exists at certain levels of the type heirarchy -- if you constantly have to up and down cast, you're probably forcing a flawed design.

              I understand inheritance is only useful with common characteristics of data, this design was meant to be quick and rough test set-up so i can try and figure out my original problem. Thanks :P

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups