• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Is it possible to cast a variable of type: dictionary<int, models.user> to dictionary<int, object> i

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Is it possible to cast a variable of type: dictionary<int, models.user> to dictionary<int, object> in C#?

 

Hi, everyone. I am working on a c# application where I have about 15 methods that Update entries in the database. So I want to make one method for update with two parameters: Dictionary<int, object> dictionary and string tableName. The 'object' part of the dictionary will accept different ViewModels. Here is my code:



But when I tried to use the above method, I receive the red underline below the parameter "Dictionary<int, user>" and the error message is: cannot convert from 'System.Collections.Generic.Dictionary<int, Models.User> to 'System.Collections.Generic.Dictionary<int, object>.

What I have tried:

I tried the following cast:

(Dictionary<int, object>)(users)

but without success. I looked for help in google and stackoverflow but did not find a similar issue. So can you tell me is it possible to cast a variable of Type: Dictionary<int, Models.User> to Dictionary<int, object> and if the answer is yes, how to do it? Thanks.
 
Saloon Keeper
Posts: 15727
368
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The problem is that both Dictionary and KeyValuePair are invariant. Dictionary<int, object> is not a supertype of Dictionary<int, user>. Normally you have to solve this by transforming the input before you pass it to the method:

There's an easier way to solve your problem though. Make your method generic:

I also changed the code to use tuple type deconstruction, but for this to work with KeyValuePair you need C# 7 and .NET Core 2.
 
Wait for it ... wait .... wait .... NOW! Pafiffle! A perfect tiny ad!
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic