I discovered a strange behavior when using property indexer (C#).
Consider the following program:
public class Program
{
public static void Main(string[] args)
{
CustomMessageList cml = new CustomMessageList
{
new CustomMessage(), // Type1
new CustomMessage(), // Type1
new CustomMessage(), // Type1
new CustomMessage(), // Type1
new CustomMessage(), // Type1
new CustomMessage() // Type1
};
// Empty
IEnumerable<CustomMessage> x1 = cml[MessageType.Type2];
// Contains all elements (6)
IEnumerable<CustomMessage> x2 = cml[0]; // MessageType.Type1 ????
// Does not compile!
IEnumerable<CustomMessage> x3 = cml[1]; // NOT MessageType.Type2 ????
}
}
public class CustomMessageList : List<CustomMessage>
{
public IEnumerable<CustomMessage> this[MessageType type]
{
get { return this.Where(msg => msg.MessageType == type); }
}
}
public class CustomMessage
{
public MessageType MessageType { get; set; }
}
public enum MessageType
{
Type1,
Type2,
Type3
}
Why do I get all results back when using the default indexer (the x2 variable)?
It seems that the int
parameter (0) is automatically converted to the enum type (Type1). This is not what I was expecting....
Thanks in advance for the explanations!