-->

Welcome to our Coding with python Page!!! hier you find various code with PHP, Python, AI, Cyber, etc ... Electricity, Energy, Nuclear Power

Tuesday 3 July 2018

C# | Better way to create objects from strings

I'm looking for a better way to create objects based off of a value of a string.

Consider the following:
Input file:
//each Vehicle type has a list of different options
//whose length varies, I provided a simple case
van*2006*dodge*grand caravan*green~
car*2010*toyota*corolla*red~
truck*2005*toyota*tundra*black~
Classes:
abstract class Vehicle: IVehicle{
    public int Year;
    public string Make;
    public string Model;

    ...
}

class Van : Vehicle
{
    ...
}

class Car : Vehicle
{
    ...
}

class Truck : Vehicle
{
    ...
}
Program:
static void Main(string[] args)
{
    char delimiter = '*';
    string fileToRead = "inventory.csv";
    string currentLine = string.Empty;
    List<IVehicle> inventory = new List<IVehicle>();

    //Open file
    using (StreamReader reader = new StreamReader(fileToRead))
    {
        //while you read each line
        while ((currentLine = reader.ReadLine()) != null)
        {
            IVehicle temp;

            //Tokenize the line 
            string[] parts = currentLine.Split(delimiter);

            switch(parts[0])
            {
                case "van":
                    temp = new Van();
                    ...
                break;
                case "car"
                    temp = new Car();
                    ...
                break;
                case "truck"
                    temp = new Truck();
                    ...
                break;
            }

            inventory.add(temp);
        }
    }

    ...
}
My problem with the code is the switch statement. It feels messy and I'm looking for a better way.

No comments:

Post a Comment

Thanks for your comments

Rank

seo