Writing a method that takes a Dictionary argument in a Zerotouch node

zerotouch
dynamo

#1

I implemented a simple class with one method that takes a Dictionary argument as follows.

public class Program
{
    static public Dictionary<string, object> ReadDictionary(Dictionary<string, object> dictionary)
    {
        return dictionary;
    }
}

My problem is that, if I pass a dictionary with mixed values including a Point like in the screenshot below, I will receive a “Warning: Object must implement IConvertible”, and the output dictionary does not include the point. Indeed, when I debugged the code and put a breakpoint on the line “return dictionary”, I can see that the input dictionary only contains 2 elements with keys “foo” and “bar”. What is my mistake here?


#2

@Aparajit_Pratap thoughts?


#3

@Michael_Kirschner2 this is a known issue. I attempted a fix but not quite there yet: https://github.com/DynamoDS/Dynamo/pull/9023. Will return to it when I get the chance.


#4

Thank you Aparajit and Michael. In the meantime I will separate the keys and values as follows.

static public Dictionary<string, object> ReadDictionary(List<string> keys, List<object> values)
{
    if(keys.Count != values.Count)
    {
        throw new Exception("Must have the same size");
    }
    Dictionary<string, object> dictionary = new Dictionary<string, object>();
    for(int i = 0; i < keys.Count; i++)
    {
        dictionary.Add(keys[i], values[i]);
    }
    return dictionary;
}


#5

You can do it like this

public static class Dictionary
{
    static public IDictionary ReadDictionary(IDictionary dictionary)
    {
        return dictionary;
    }
}


#6

Many thanks Erik, that worked.
For the record, the IDictionary class in your code comes from System.Collections, instead of System.Collections.Generic.


#7

I try to keep input and return output as generic as possible. Inside the methods, I then need to convert the items to strong types when needed. It takes more lines of code, but it gives also flexibility. However, if I want users to feed the input with a certain type, then I do use strongly defined collections.

In your question, you feed the data with different types, so I figured that an Interface Dictionary would be what was needed and not a strong defined Dictionary.

System.Collections
The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.

System.Collections.Generic
The System.Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/yy580hbd(v=vs.110)