Hello. There is a certain IChatAttributes interface from which certain classes are inherited ( AiAttributes , NavAttributes , ContentAttributes .. - these classes are created using the Singleton pattern). There is also a class ChatAttributes which in the constructor creates instances of the heirs and puts them into its only property List<IChatAttributes> AttributesList need to write a generalized method that will retrieve from the AttributesList objects of the heir classes and return them.

I did this:

 public T GetCurrentAttribute<T>() { T returnedObject = default(T); foreach (var item in AttributesList) { if (item is T) returnedObject = (T)item; else returnedObject = default(T); } return returnedObject; } 

Now I'm modeling the situation:

attributesList generated and contains two IChatAttributes ( AiAttributes and ContentAttributes ) ContentAttributes . Using an asynchronous method in another class, I want to extract these objects using the above generalized method:

  var aiObj= await Task.Factory.StartNew(() => attribute.GetCurrentAttribute<AiRoutAttributes>()); var cntObj= await Task.Factory.StartNew(() => attribute.GetCurrentAttribute<ContentAttributes>()); 

as a result, data comes to cntObj not to cntObj .

Where I missed something, help me figure it out.

Reported as a duplicate by Pavel Mayorov c # 11 May '18 at 9:11 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • The question was not that the conditional method works in both branches, but the need to write the correct generalized method. @Andrew NOP Offered the optimal variant of the method without using conditional construction. - Roman Timokhov
  • Well, Pavel Mayorov is also partly right here, your code finds the item you need, but the next iteration will simply overwrite returnedObject , so the search result will be lost. Your code can be fixed simply by deleting the else branch inside the loop :) In my version, the conventional design is simply hidden inside OfType , well, I just showed how you can use the standard tools of the standard library. - Andrey NOP
  • @ RomanTimokhov The question in its current formulation was that the method did not work for you. I explained why. - Pavel Mayorov

1 answer 1

Your implementation of GetCurrentAttribute is incorrect. Just look at the progress of the method under the debugger, an error on the surface.

In general, you can also rewrite it easier, something like this:

 return AttributesList.OfType<T>().FirstOrDefault(); // Или SingleOrDefault, если нужно контролировать, что запись такого типа ровно одна