Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# – CS0572 Error When Trying to Populate a Class

C# Newbie Here.

I have a class below:

namespace CompanyDevice.DeviceResponseClasses
{
    public class DeviceStatusClass
    {
        public class Root
        {
            public static string RequestCommand { get; set; }
        }
    }
}

In another namespace I have:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

namespace CompanyDevice
{
    public class StatusController : ApiController
    {
        public  DeviceStatusClass Get()
        {
            var returnStatus = new DeviceStatusClass();
            returnStatus.Root.RequestCommand = "Hello"; //'Root' is causing a CS0572 error

            return returnStatus;
        }
    }
}

I’m sure I’m making some rudimentary error here. Could you please help me find it? Thanks.

>Solution :

You access static properties from the type, not from the instance.

DeviceStatusClass.Root.RequestCommand = "Command";

Because the property RequestCommand is static, there will only ever be one. Perhaps this is what you want, but likely is not based on your usage.

You can remove the static keyword from RequestCommand, then you can access it through the instance, however you will need to add a field or property for the instance of Root inside of DeviceStatusClass.

public class DeviceStatusClass
{
    public Root root = new Root();

    public class Root
    {
        public string RequestCommand { get; set; }
    }
}

And use like you did originally.

public class StatusController : ApiController
{
    public  DeviceStatusClass Get()
    {
        var returnStatus = new DeviceStatusClass();
        returnStatus.root.RequestCommand = "Hello";

        return returnStatus;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading