Home > OS >  C# - CS0572 Error When Trying to Populate a Class
C# - CS0572 Error When Trying to Populate a Class

Time:04-28

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:

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.

CodePudding user response:

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;
    }
}

CodePudding user response:

You maybe have a java background. In c# nested classes only change the names, they do not make the parent class contain an instance of a child class

namespace CompanyDevice.DeviceResponseClasses
{
    public class DeviceStatusClass
    {
        public class Root
        {
            public static string RequestCommand { get; set; }
        }
        public Root DeviceRoot {get;set;} <<<=== add this
    }
}

and then

     returnStatus.DeviceRoot.RequestCommand = "Hello";
  •  Tags:  
  • c#
  • Related