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);
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With