-1

I'll show my question with an example:

ChromeDriver chrome = new ChromeDriver();
chrome.Capabilities.GetCapability("chrome");

Returns an object which is of type Dictionary<string, object>. Inside this object there's a key userDataDir whose value I need.

Do I have to cast the object to a dictionary first or can I do some one-liner like:

chrome.Capabilities.GetCapability("chrome").GetType().GetProperty("userDataDir").GetValue()

The line above isn't compiled just to clarify.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
Moshisho
  • 2,781
  • 1
  • 23
  • 39

2 Answers2

1

If the returntype of chrome.Capabilities.GetCapability("chrome"); is Dictionary<string, object>

You can do as following, by casting the returned object to a Dictionary :

var capability = (Dictionary<string, object>)chrome.Capabilities.GetCapability("chrome");
var userDataDir = capability["userDataDir"];
Jonas W
  • 3,200
  • 1
  • 31
  • 44
1

You could do the cast on one line with as

var userDataDir = (chrome.Capabilities.GetCapability("chrome") as Dictionary<string, object>)["userDataDir"];

Of course this opens you up to possible null reference exceptions. With C# 6 you could use the null-conditional to mitigate that.

var userDataDir = (chrome.Capabilities.GetCapability("chrome") as Dictionary<string, object>)?["userDataDir"];

But then you would not know if null was a value in the dictionary or if it was null because the cast failed. The best bet is just to do this in multiple lines.

var dic = chrome.Capabilities.GetCapability("chrome") as Dictionary<string, object>;
if(dic == null)
{
    // The capability isn't a dictionary.
}
else
{
    var userDataDir = dic["userDataDir"];
}
juharr
  • 31,741
  • 4
  • 58
  • 93
  • Actually in my case it can't be null, because that will indicate that the functionality is wrong at the first place. – Moshisho Feb 04 '16 at 15:47