Home > Enterprise >  Accessing List inside A class
Accessing List inside A class

Time:10-17

Why can't I add values to the list inside a created class? ex. I write carType_list.add

class Vehicles
{
    List<string> carType_list = new List<string>();
    List<string> carModel_list = new List<string>();
    List<int> seatCapacity_list = new List<int>();
    List<string> mileageLimit_list = new List<string>();
    List<double> ratings_list = new List<double>();
    List<double> rentPrice_list = new List<double>();
}

CodePudding user response:

Use Constructor

A better way to initialize all class variables is to use a constructor. The constructor is like a method but it is called when an object of that class is created. You can do like:

class Vehicles
{
    List<string> carType_list = new List<string>();
    // ... fields
    
    // constructor
    Vehicle(){
        carType_list.Add("4 wheeler");
    }
    // ... constructors or functions
    // add car or type methods, etc.
}

A better way (Getters and Setters)

Currently, the fields are not public, so they can't be accessed outside the class. It is highly encouraged to use the getters and setters instead of making them public if you want to update the field outside the class, like:

class Vehicles
{
    // declare fields with get, set
    public List<string> carType_list{ get; set; }
    // ... fields
    
    public constructor(){
        carType_list = new List<string>(); // initilize
        carType_list.Add("4 wheeler"); // add value
    }
    // ... constructors or functions
    // add methods or some
}

Static Constructor

  • Only static fields can be initizlied this way.

If the class has some static attributes that need to be initiated without instantiating class. You can use static constructor for that.

class Vehicles
{
    static List<string> carType_list = new List<string>();
    // ... fields
    
    // static constructor
    static Vehicle(){
        carType_list.Add("4 wheeler");
    }
    // ... constructors or functions
}

CodePudding user response:

You need to make the class and its members public in order to manipulate it from the outside:

public class Vehicles
{
    public List<string> carType_list = new List<string>();
    public List<string> carModel_list = new List<string>();
    public List<int> seatCapacity_list = new List<int>();
    public List<string> mileageLimit_list = new List<string>();
    public List<double> ratings_list = new List<double>();
    public List<double> rentPrice_list = new List<double>();
}

Then you can call Add() on each of the lists from the outside. If the fields remain private, you would only be able to populate the lists from within your class, e.g. the Constructor or any non-static class method.

Ideally, you would move the initialization to the Constructor and then add values from anywhere else, inside or outside of your class, depending on your use cases.

  •  Tags:  
  • c#
  • Related