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 7637199
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T07:52:42+00:00 2026-05-31T07:52:42+00:00

I essentially want to do this: if(obj is IDictionary) { return { + string.Join(Environment.NewLine,

  • 0

I essentially want to do this:

if(obj is IDictionary)
{
    return "{" + string.Join(Environment.NewLine, ((IDictionary)obj).Cast<DictionaryEntry>().Select(e => string.Format("  {0}: {1}", PrettyString(e.Key), PrettyString(e.Value)))) + "}";
}

But I keep getting an invalid cast. I can do

foreach(DictionaryEntry e in (IDictionary)obj)

So why can’t I do this?


I find this quite curious. I wrote an extension to solve the problem:

static class EnumerableExt
{
    public static IEnumerable<DictionaryEntry> Entries(this IDictionary dict)
    {
        foreach (var item in dict) yield return (DictionaryEntry)item;
    }
}

Then I can just do:

((IDictionary)obj).Entries().Select(...)

The curious part is that Resharper tells me I can replace my extension with this:

return dict.Cast<DictionaryEntry>();

But that throws an exception. Is this a bug in Resharper? Or how Cast works? I’d imagine Cast would work exactly the way my extension does.

Edit: Ah.. I read this answer a bit more closely. Still strange.

  • 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-05-31T07:52:43+00:00Added an answer on May 31, 2026 at 7:52 am

    Are the key and value types known at compile time? If so, you could make a generic method for the pretty-print and let the compiler infer the types for you, like:

    static void Main(string[] args)
    {
        var obj = new Dictionary<string, string>()
            {
                { "foo", "bar" },
                { "baz", "ack" },
            };
    
        var stringVersion = GetStringVersion(obj);
    
        Console.WriteLine(stringVersion);
    }
    
    private static string GetStringVersion<TKey, TValue>(Dictionary<TKey, TValue> dict)
    {
        return "{" + string.Join(Environment.NewLine, dict.Select(e => string.Format("  {0}: {1}", e.Key, e.Value))) + "}";
    }
    

    In terms of the behavior you’re seeing, it’s a known weird case due to backwards compat and a design decision:

    http://blogs.msdn.com/b/bclteam/archive/2004/09/03/225473.aspx

    We discussed a problem with implementation of IEnumerable on
    Dictionary. What type should IEnumerable.GetEnumerator().Current
    return? KeyValuePair or DictionaryEntry? Same for
    ICollection.CopyTo. Instances of what type should be copied to the
    array?

    We decided the following:

    1. IEnumerable and ICollection interface implementations will use KeyValuePair<K,V> as the item type.
    2. IDictionary specific members (GetEnumerator returning IDictionaryEnumerator) will use DictionaryEntry as the item type.

    The reason is that we are in a process of making a change where IEnumerator<T> would extend IEnumerator. It would be very strange if walking the hierarchy from Dictionary<K,V>->IEnumerable<T>->IEnumerable we suddenly changed the type of the item returned from enumerators.

    Due to that design decision (during the creation of .NET 2.0), when you operate on the non-generic IEnumerable, the GetEnumerator() call returns IDictionaryEnumerator, and the resulting items are of type DictionaryEntry (presumably for back-compat with Hashtable-type iteration). However, once you are calling the generic IEnumerable (which is what happens once you do Cast() or OfType(), you’ll get KeyValuePair items instead.

    Note that this is a particular oddity about using Dictionary in a non-generic context – Hashtable (still) iterates as DictionaryEntry items just fine, and ‘normal’ iteration over Dictionary gives you KeyValuePair items.

    As others have said, you should stick with the generic access if you can, since it’ll let you avoid this little ‘gotcha’ in the design decisions of Dictionary.

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

Sidebar

Related Questions

I essentially want to split up a string based on the sentences, therefore (for
I essentially want to search the frequency of a string. For example, if I
I essentially want to spider my local site and create a list of all
Essentially I want to know if in VB.NET 2005 if using a sqlcommand and
We have a reverse proxy here, running Apache in version 2.2.x Essentially I want
Essentially what I want to do is to apply additional CSS classes to individual
If I want to essentially grep every line ever in the repository, is there
I want to write a piece of software which is essentially a regex data
Essentially, what I want to do (in DirectX) is to take two partially-transparent images
I want to store a list of numbers (essentially, a set in mathematical terms)

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.