Get var type value in C#

344 Views Asked by At
var temp = toCheck.GetData(DataFormats.FileDrop);

I have the code above in my program. toCheck is an IDataObjecct containing a file(image to be specific) path.

When I debug, I see the value stored under as such:
temp -> {string[1]}
[0] -> "C:\....rest of path"

Everything is correct but when I try to access the string inside, I cannot. If I use the toString() method it returns System.String[] but not the filepath.
Any suggestions on how I can retrieve the filepath inside of the variable?

3

There are 3 best solutions below

3
On

temp is an array of strings, that is why you are getting that. If you want to get the first string of the array then:

var mystring = temp[0];

That should do

Also you can check if the string[] has any string with:

if(temp.Length > 0) myString = temp[0];

where myString is a variable of type string

2
On

temp -> {string[1]} Means that temp is an array of type string with one element.

[0] -> "C:\....rest of path" Means that the element at index 0 is equal to the path.

Since GetData returns the string array boxed as an object, you'll also have to unbox it first. Then you can simply access that element like this:

string[] strArr = temp as string[];
string s = temp[0];
0
On

I found the answer!

string[] arr = ((IEnumerable)temp).Cast<object>().Select(x => x.ToString()).ToArray();

Using the above statement you can go from type object to an array of string.
You need to have included using.System.Linq for it to work.

 var temp = toCheck.GetData(DataFormats.FileDrop);
        string[] arr = ((IEnumerable)temp).Cast<object>().Select(x => x.ToString()).ToArray();
        string path = "";

        foreach(string a in arr)
            path = a;

This ended up being all the code if anybody is curious. I iterate over the array because otherwise it would skip the rest of the function when I debugged. Not sure what was causing this but this works. Thank you all for your help!