Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding dictionaries, adding new values to the dictionary using c#

If I have Customer object which have Payment property which is dictionary of custom enum type and decimal value like

Customer.cs
public enum CustomerPayingMode
{
   CreditCard = 1,
   VirtualCoins = 2, 
   PayPal = 3
}
public Dictionary<CustomerPayingMode, decimal> Payment;

In client code I have problem with adding values to the Dictionary, tried like this

Customer cust = new Customer();
cust.Payment = new Dictionary<CustomerPayingMode,decimal>()
                      .Add(CustomerPayingMode.CreditCard, 1M);
like image 954
user1765862 Avatar asked Jan 14 '23 20:01

user1765862


2 Answers

The Add() methode does not return a value which you can assign to cust.Payment, you need to create the dictionary then call the Add() methode of the created Dictionary object:

Customer cust = new Customer();
cust.Payment = new Dictionary<CustomerPayingMode,decimal>();
cust.Payment.Add(CustomerPayingMode.CreditCard, 1M);
like image 85
CloudyMarble Avatar answered Feb 15 '23 17:02

CloudyMarble


You could initialize the dictionary inline:

Customer cust = new Customer();
cust.Payment = new Dictionary<CustomerPayingMode, decimal>()
{
    { CustomerPayingMode.CreditCard, 1M }
};

You might also want to initialize the dictionary inside of the Customer constructor and let users add to Payment without having to initialize the dictionary:

public class Customer()
{
    public Customer() 
    {
        this.Payment = new Dictionary<CustomerPayingMode, decimal>();
    }

    // Good practice to use a property here instead of a public field.
    public Dictionary<CustomerPayingMode, decimal> Payment { get; set; }
}

Customer cust = new Customer();
cust.Payment.Add(CustomerPayingMode.CreditCard, 1M);
like image 33
Andrew Whitaker Avatar answered Feb 15 '23 15:02

Andrew Whitaker