Search code examples
c#inheritancecastingstack-overflowboxing

C# type casting in class from own superclass


The codes that I write from the source code of a project are below. I got that codes through a decompiler. Program is working good when I install normally but when I compile the source codes, it throws exception below.

Is this possible;

public abstract class ComPortSettingsBase
{
}

public class ComportSettings: ComPortSettingsBase
{
}

public abstract class Comport
{
    public ComPortSettingsBase Settings
    {
        get
        {
            return this.settings;
        }
        set
        {
            this.settings = value;
        }
    }
}

public class ComportSetup: Comport
{
    public ComportSettings Settings
    {
        get
        {
           return (ComPortSettings)base.Settings
        }
        set
        {
           // The problem is here.
           // Firts of all type casting is not valid. It causes type casting exception
           // If I remove the type casting it causes stackoverflow exception normally. 

           this.Settings = (ComPortSettingsBase)value;
        }
    }
}

Solution

  • Try this

    public class ComportSetup: Comport
    {
        public ComportSettings Settings
        {
            get
            {
               return (ComportSettingsBase)base.Settings
            }
            set
            {
               base.Settings = (ComPortSettingsBase)value;
            }