Conversione between Hashtable and IDictionary

  • Thread starter Thread starter Emilio
  • Start date Start date
E

Emilio

Good Morning,
I've the class :

public class GenericOutput
{
public String answer;
public IDictionary<string,string> maincontent;

public GenericOutput()
{
answer = null;
maincontent = null;
}
}

and in another class I have:

GenericOutput op = new GenericOutput();
op.maincontent = new Hashtable();

At this point the complimer give me the error

"Cannot implicitly convert type 'System.Collections.Hashtable' to
'System.Collections.Generic.IDictionary<object,object>'. An explicit
conversion exists (are you missing a cast?) "

Where am i wrong? May you help me?
Thank you,

Emilio
 
[...]
            GenericOutput op = new GenericOutput();
            op.maincontent = new Hashtable();
At this point the complimer give me the error
"Cannot implicitly convert type 'System.Collections.Hashtable' to
'System.Collections.Generic.IDictionary<object,object>'. An explicit
conversion exists (are you missing a cast?) "
Where am i wrong? May you help me?

Hashtable doesn't implement IDictionary<TKey, TValue>.

You can either use the non-generic IDictionary interface in your  
"GenericOutput" class, or you can use a collection implementation that  
does implement IDictionary<TKey, TValue> (i.e. Dictionary<TKey,  
TValue>...in your case, specifically Dictionary<string, string>).

Pete


Thank you Pete.
Best regars, Emilio
 
IDictionary<TKey, TValue> is the generic equivalent(ish) to hashtable and in
fact should give better performance so change the calling code.

To use lazy loading of maincontent do this but remember it will fail over
SOAP.

public class GenericOutput
{
String answer;
public string Answer { get{....} set{....}}

IDictionary<string,string> maincontent;
public IDictionary<string,string> Answer
(
get
{
if (maincontent == null)
maincontent = new IDictionary<string,string>()

return maincontent;
}
set{....}
)

public GenericOutput()
{
}
}
 
Back
Top