Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8630667
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T09:06:27+00:00 2026-06-12T09:06:27+00:00

private Dictionary<Type, List<IDataTransferObject>> dataStore = new Dictionary<Type, List<IDataTransferObject>>(); public void Insert<T>(T dto) where T

  • 0
private Dictionary<Type, List<IDataTransferObject>> dataStore = new Dictionary<Type, List<IDataTransferObject>>();

public void Insert<T>(T dto) where T : IDataTransferObject
{
    if (!dataStore.ContainsKey(typeof(T)))
    {
        dataStore.Add(typeof(T), new List<T>());
    }

    dataStore[typeof(T)].Add(dto);
}

The above code gives me a compile error on the dataStore.Add line because it doesn’t like me trying to assign a List<T> to a List<IDataTransferObject>. Since my method restricts T to only IDataTransferObject’s shouldn’t the covariance/contravariance stuff in .Net 4 allow this code?

I know I can change it to do new List<IDataTransferObject> and it will work, but I’m curious why the original code doesn’t work.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T09:06:28+00:00Added an answer on June 12, 2026 at 9:06 am

    Pretty sure a List<SubClass> isn’t covariant to List<BaseClass>. IEnumerable<T> maybe, but not List as you can freely add a non-T (but still IDataTransferObjects) which would throw a runtime exception so it’s caught at compile time.

    While your code might be safe at runtime (as you use keys by type), the compiler doesn’t know this.

    List<Animal> animalList = new List<Animal>();
    animalList.Add(new Dog()); //ok!
    
    List<Cat> catList = new List<Cat>();
    animalList = catList; //Compiler error: not allowed, but it's what you're trying to do
    animalList.Add(new Dog()) //Bad stuff! Trying to add a Dog to a List<Cat>
    

    What you’re doing would work if you were trying to treat it as IEnumerable<IDataTransferObject> as those cannot by modified by code (unless you cast it first at which point it would pass/fail if you use a bad type). But List can definitely be altered by compile-time code.

    EDIT: If you don’t mind casting, and really want a List<T> (so your calling code is typesafe and not adding non-T objects once retrieved) you might do something like this:

    private Dictionary<Type, object> dataStore = new Dictionary<Type, object>();
    
    public void Insert<T>(T dto) where T : IDataTransferObject
    {
        object data;
        if (!dataStore.TryGetValue(typeof(T), out data))
        {
            var typedData = new List<T>();
            dataStore.Add(typeof(T), typedData);
            typedData.Add(dto);
        }
        else
        {
            ((List<T>)data).Add(dto);
        }
    }
    
    
    //you didn't provide a "getter" in your sample, so here's a basic one
    public List<T> Get<T>() where T : IDataTransferObject
    {
        object data;
        dataStore.TryGetValue(typeof(T), out data);
        return (List<T>)data;
    }
    

    Calling code is like:

    Insert(new PersonDTO());
    Insert(new OrderDTO());
    Insert(new PersonDTO());
    
    List<PersonDTO> persons = Get<PersonDTO>();
    List<OrderDTO> orders = Get<OrderDTO>();
    
    Console.WriteLine(persons.Count); //2
    Console.WriteLine(orders.Count); //1
    

    So from the outside, all API usage is typesafe. Instead of orders being a List<IDataTransferObject> (which means you can add non-OrderDTO objects), it’s strongly typed and cannot be mixed and matched.

    Of course at this point, there’s no real need to constrain to IDataTransferObject, but that’s up to you and your API/design/usage.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

private final List<KeyListener> keyListeners= new CopyOnWriteArrayList<KeyListener>(); public void addKeyListener(KeyListener keyListener){ keyListeners.add(keyListener); } In the
private static Dictionary<Type, Func<string, object>> _parseActions = new Dictionary<Type, Func<string, object>> { { typeof(bool),
Here's what I have private readonly Dictionary<Type, List<object>> _cache; public IList<T> Get<T> (Expression<Func<T, bool>>
The code: [1] private delegate void ThreadStatusCallback(ReceiveMessageAction action, Dictionary<int, List<string>> message); [2] Dictionary<int, List<string>>
I have the following code: private Dictionary<int, Entity> m_allEntities; private Dictionary<Entity, List<IComponent>> m_entityComponents; public
public class ContactsController : ApiController { private static readonly List<Contact> _contacts = new List<Contact>();
I got next code: private Dictionary<int?, byte[]> GetAllLocalScanFiles() { using (DZine_IStylingEntities ctxLocal = new
I have the following decleration: private Dictionary<string, Dictionary<string, File>> listFiles = new Dictionary<string,Dictionary<string,File>>(); How
I have a dictionary which is keyed by a List: private Dictionary<List<custom_obj>, string> Lookup;
The class looks as follows: public static class CacheManager { private static Dictionary<string, object>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.