Sandalj
Sandalj

Reputation: 1

Why does my if syntax not work in these conditions?

my method

 public void Add(Car car)
     {
         if (car.DailyPrice > 10 && car.BrandName.Length > 2)
         {
             _cars.Add(car);
         }
          else {
             Console.WriteLine("Error");
         }

--- i could not get error message in here:

 public static void Main(string[] args)
   {
       CarManager carManager = new CarManager(new InMemoryCarDal());

       
       List<Car> _cars = new List<Car>();
       {

           //foreach (var car in carManager.GetAll())
           //{
           //    Console.WriteLine(" Brand: " + car.BrandName);

           //}

            static void Main()
           {
     

               Car newCar1 = new Car
              
               {
                   Id = 7,
                   BrandId = 4,
                   ColorId = 12,
                   DailyPrice = 8,
                   Description = "Cheap Car",
                   ModelYear = 2023,
                   BrandName = "C"
               };
               InMemoryCarDal inMemoryCarDal = new InMemoryCarDal();
               inMemoryCarDal.Add(newCar1);
               

           }

I should get an error message for second new car(id2). But I don't see any error, and it does work, and I can see it on my console.

What am I doing wrong in here? Maybe it is so simple thing but I am starter in software.

I am trying to get error message if car's price is lower than 10 and brand of car's name is lower than 2 character.

Upvotes: -1

Views: 156

Answers (2)

flackoverstow
flackoverstow

Reputation: 726

Are you assuming the compiler will take your initializer there:

        _cars = new List<Car> 
            {
                new Car { Id = 1, BrandId = 1, ColorId = 13, DailyPrice = 30000, Description = "BMW 5.20", ModelYear = 2023, BrandName = "BMW" },
                new Car { Id = 2, BrandId = 1, ColorId = 13, DailyPrice = 5, Description = "BMW 5.20", ModelYear = 2023, BrandName = "B" },
                new Car { Id = 3, BrandId = 3, ColorId = 10, DailyPrice = 25000, Description = "Mercedes C180", ModelYear = 2023, BrandName = "Mercedes" },
                new Car { Id = 4, BrandId = 5, ColorId = 11, DailyPrice = 21000, Description = "Hyundai i20n", ModelYear = 2023, BrandName = "BMW" },
                new Car { Id = 5, BrandId = 3, ColorId = 10, DailyPrice = 40000, Description = "Mercedes A180", ModelYear = 2023, BrandName = "Mercedes" },
            };

And call your custom Add method for each one?

The compiler won't do that.

If you want that to happen, you can do something like this:

{
    //assign your cars to a temp variable
    var carsToAdd = new List<Car> 
                {
                    new Car { Id = 1, BrandId = 1, ColorId = 13, DailyPrice = 30000, Description = "BMW 5.20", ModelYear = 2023, BrandName = "BMW" },
                    new Car { Id = 2, BrandId = 1, ColorId = 13, DailyPrice = 5, Description = "BMW 5.20", ModelYear = 2023, BrandName = "B" },
                    new Car { Id = 3, BrandId = 3, ColorId = 10, DailyPrice = 25000, Description = "Mercedes C180", ModelYear = 2023, BrandName = "Mercedes" },
                    new Car { Id = 4, BrandId = 5, ColorId = 11, DailyPrice = 21000, Description = "Hyundai i20n", ModelYear = 2023, BrandName = "BMW" },
                    new Car { Id = 5, BrandId = 3, ColorId = 10, DailyPrice = 40000, Description = "Mercedes A180", ModelYear = 2023, BrandName = "Mercedes" },
                };

    //iterate over your temp variable calling your custom Add method yourself
    _cars = new List<Car>();
    foreach(var carToAdd in carsToAdd){

        Add(carToAdd); //call my custom Add method below

    }

}

public void Add(Car car)
{
    if (car.DailyPrice > 10 && car.BrandName.Length > 2)
    {
         _cars.Add(car);
    }
    else 
    {
         Console.WriteLine("Error");
    }
}

With your code how it is, we can use a website called sharplab.io to find out what the compiler does (I've edited your code a bit for brevity):

enter image description here

SharpLab compiles your code then decompiles it again so you can see, for the code you write, what the compiler transforms it into. The compiler actually does huge amounts of rewriting of your code. Mostly these days new features are not added to C# by changing the language itself; most of the improvements are in finding nicer, neater ways to let you write code, and then have the compiler transform them into the "old way" it would have been written (in say, .net framework 2.0 syntax)

You can see that your initializer with the 5 cars in, just becomes a Car car1 = new Car {... }; _list.Add(car1)

Your custom Add method that does the checking of the name length is never called by the compiler; the compiler expands that initializer straight to a set of "create, direct add, create, direct add"

The only way to get what you want if you want to use that nice compact initializer syntax is to run over the collection after and call your own Add method

You could also write this:

_list = new ...
Add(new Car { Id = 1, BrandId = 1, ColorId = 13, DailyPrice = 30000, Description = "BMW 5.20", ModelYear = 2023, BrandName = "BMW" }});
Add(new Car { ... });
Add(new Car { ... });
Add(new Car { ... });
...

i.e. call your Add method passing a new car each time. It's about the same number of characters typed, as using the initializer. All in, you have to be the one to call your custom Add method; the compiler won't

Upvotes: 1

Manas Maratkar
Manas Maratkar

Reputation: 11

Your code looks incomplete also the question you asked is not really understandable.

From what I got this should help:

using System;
using System.Collections.Generic;

public class Car
{
    public int Id { get; set; }
    public int BrandId { get; set; }
    public int ColorId { get; set; }
    public decimal DailyPrice { get; set; }
    public string Description { get; set; }
    public int ModelYear { get; set; }
    public string BrandName { get; set; }
}

public class CarManager
{
    private List<Car> _cars = new List<Car>
    {
        new Car { Id = 1, BrandId = 1, ColorId = 13, DailyPrice = 30000, Description = "BMW 5.20", ModelYear = 2023, BrandName = "BMW"},
        new Car { Id = 2, BrandId = 1, ColorId = 13, DailyPrice = 5, Description = "BMW 5.20", ModelYear = 2023, BrandName= "B"},
        new Car { Id = 3, BrandId = 3, ColorId = 10, DailyPrice = 25000, Description = "Mercedes C180", ModelYear = 2023, BrandName="Mercedes"},
        new Car { Id = 4, BrandId = 5, ColorId = 11, DailyPrice = 21000, Description = "Hyundai i20n", ModelYear = 2023, BrandName= "BMW"},
        new Car { Id = 5, BrandId = 3, ColorId = 10, DailyPrice = 40000, Description = "Mercedes A180", ModelYear = 2023, BrandName="Mercedes"},
    };

    public void Add(Car car)
    {
        if (car.DailyPrice > 10 && car.BrandName.Length > 2)
        {
            _cars.Add(car);
        }
        else
        {
            Console.WriteLine("Error: The car must have a daily price greater than 10 and a brand name longer than 2 characters.");
        }
    }
}

class Program
{
    static void Main()
    {
        CarManager carManager = new CarManager();

        Car newCar1 = new Car
        {
            Id = 6,
            BrandId = 2,
            ColorId = 14,
            DailyPrice = 15000,
            Description = "Audi A4",
            ModelYear = 2023,
            BrandName = "Audi"
        };

        Car newCar2 = new Car
        {
            Id = 7,
            BrandId = 4,
            ColorId = 12,
            DailyPrice = 8,
            Description = "Cheap Car",
            ModelYear = 2023,
            BrandName = "CC"
        };

        carManager.Add(newCar1); // This should be added successfully.
        carManager.Add(newCar2); // This should print an error message.
    }
}

Explanation:

  1. Car Class: Defines the properties of a car.
  2. CarManager Class: Contains a list of cars and a method Add to add new cars to the list based on specific conditions.
  3. Add Method: Checks if the car's daily price is greater than 10 and the brand name's length is more than 2 characters before adding it to the list. If conditions are not met, it prints an error message.
  4. Program Class: Demonstrates adding new cars using the CarManager class and shows how the Add method works with both valid and invalid inputs.

The given solution ensures that only cars meeting the specified criteria are added to the list, maintaining the integrity of the car collection.

Upvotes: 1

Related Questions