Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to create a DTO called "device" that I'm trying to add to a list called "deviceList". However, when I try to add my device to the deviceList, it tells me 'The name 'device' does not exist in the current context'.

public static device_DTO device= new device_DTO()
{
    DeviceTypeId = 33,
    DeviceTypeName = "BPD",
    Product = "Very Good Meter",
    DeviceClass = "Battery Powered Device",
    Form = "2S",
    HardwareVersion = "HW V3"
};

public static List<device_DTO> deviceList= new List<device_DTO>();
deviceList.Add(device);


What I have tried:

Making the variables non-static, however that did nothing.
Posted
Updated 2-Dec-20 4:18am
Comments
BabyYoda 2-Dec-20 9:58am    
So this line
deviceList.Add(device);
says device does not exist. Well, the compiler is not lying. It does not exist. You need to write code to make it exist. Although I imagine you would actually get a null reference exception so it feels like you're leaving something out.
Richard MacCutchan 2-Dec-20 10:15am    
You need to put the last line inside a method for it to do anything. I just tested it in the correct place and it works fine.

You haven't shown where you have placed the Add line. If it's directly within the class, that's not allowed - code must be within a method.

If you want a static list initialized with a single item, you can use a collection initializer:
C#
public static readonly List<device_DTO> deviceList = new List<device_DTO>
{
    new device_DTO
    {
        DeviceTypeId = 33,
        DeviceTypeName = "BPD",
        Product = "Very Good Meter",
        DeviceClass = "Battery Powered Device",
        Form = "2S",
        HardwareVersion = "HW V3"
    }
};
However, you need to check how you are using the list to decide whether a static variable is the correct choice here.
 
Share this answer
 
You can't write executable code outside of a method, and you can't declare public or private variables inside a method.
So one of these is in the wrong place:
C#
public static device_DTO device= new device_DTO() {...}
public static List<device_DTO> deviceList= new List<device_DTO>();
Or
C#
deviceList.Add(device);


And there is a very good chance than none of those should be static anyway ...
 
Share this answer
 
You need to fully qualify "device". "device" is just the name of the field on the class it was defined on. To use it you need to use "ClassName.device" rather than just "device".

However I have to question the logic in adding a static item to a List, there is probably a general issue with what it is you're trying to achieve, or how you are trying to achieve it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900