Search code examples
c#console.writelineformatexception

System.FormatException in WriteLine


I'm having a trouble in my code with this exception:

enter image description here

System.FormatException

Additional information: Input string was not in a correct format.

I have two files in my visual studio C# solution:

  1. Program.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace EventPubSub
    {
        class Program
        {
            static void Main(string[] args)
            {
                Rectangle rect = new Rectangle();
                // Subscribe to the Changed event
                rect.Changed += new EventHandler(Rectangle_Changed);
                rect.Length = 10;
            }
            static void Rectangle_Changed(object sender, EventArgs e)
            {
                Rectangle rect = (Rectangle)sender;
                Console.WriteLine("Value Changed: Length = { 0}", rect.Length);
            }
        }
    }
    
  2. file Rectangle.cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace EventPubSub
    {
        class Rectangle
        {
            //Declare an event named Changed of
            //delegate type EventHandler
    
            public event EventHandler Changed;
    
            private double length = 5;
    
            public double Length
            {
                get
                {
                    return length;
                }
                set
                {
                    length = value;
                    //Publish the Changed event
                    Changed(this, EventArgs.Empty);
                }
            }
        }
    }
    

The exception arise when I execute the line: rect.Length = 10;


Solution

  • there is a space between { and 0 in the handler which is leading to the exception