c# - Is it possible to access child object properties from a List of a base object? -


i have base message objects , many more specific message objects inherit message object. want able store messages list of lists. need able find index of outer list there child message particular property value. (for specific project, order in add messages list same, know message @ index.)

namespace project {     public class message {} //base class } 

here's 2 example child messages:

class abcmessage : message {     public abcmessage() { }      public string abcproperty1 { get; set; }     public string abcproperty2 { get; set; }     public string abcproperty3 { get; set; } }   class xyzmessage : message {     public xyzmessage() { }      public string xyzproperty1 { get; set; }     public string xyzproperty2 { get; set; } } 

and here want do:

public static list<list<message>> messagelist;  abcmessage abcmessage = new abcmessage(); abcmessage.abcproperty1 = 1; abcmessage.abcproperty2 = 2; abcmessage.abcproperty3 = 3; list<message> mylist = new list<message>(); mylist.add(abcmessage);  //...  int index; (int = 0; < messagelist.count; i++) {     if (messagelist[i][0].abcproperty2 == 5) {         index = i;         break;     } } 

however, problem i'm not able call property (or property matter). know how solve problem? perhaps need put properties in message class? (the reason wanted inheritance make easier make list of lists.)

the solution cast each message abcmessage , then, if not null, it's instance of abcmessage , can have it's properties tested:

int index; (int = 0; < messagelist.count; i++)  {     var message = messagelist[i][0] abcmessage;     if (message != null && message.abcproperty2 == 5)      {         index = i;         break;     } } 

as not likes as/test null approach, other option use is:

for (int = 0; < messagelist.count; i++)  {     var message = messagelist[i][0] abcmessage;     if (messagelist[i][0] abcmessage && (abcmessage)(messagelist[i][0]).abcproperty2 == 5)      {         index = i;         break;     } } 

however, of c# 6, new option (the null-conditional operator or "elvis operator" it's known) exists, uses best of both worlds:

for (int = 0; < messagelist.count; i++) {     var message = messagelist[i][0] abcmessage;     if (message?.abcproperty2 == 5)     {         index = i;         break;     } } 

the message?.abcproperty2 == 5 syntax tests abcproperty2 if message not null, removing need != null test.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -