DFENS
DFENS

Reputation: 319

C# Dictionary Extension method syntax

I'm trying to write an extension method for dictionaries to shorten the TryGetValue syntax.

This is the extension and the exact same logic in a normal method.

private static List<T> TryGet<T>(this Dictionary<int, List<T>> dict, int key) 
{
    return dict.TryGetValue(key, out var output) ? output : new List<T>();
}

private static List<T> TryGet<T>(Dictionary<int, List<T>> dict, int key) 
{
    return dict.TryGetValue(key, out var output) ? output : new List<T>();
}

var works = TryGet(MyDict, MyInt);
var doesntWork = MyDict.TryGet...

The code simply does not find the extension. I made triple sure that the dictionary is the same and of the right type.

I have the extension code in a file with other working extensions, so that's not the problem either.

Upvotes: 0

Views: 1947

Answers (2)

Anu Viswan
Anu Viswan

Reputation: 18155

The extension methods needs to be accessible for the calling method and should be defined in a static class. In the OP, it is likely that it was defined in a non-static class

public static class Extensions
{
public static List<T> TryGet<T>(this Dictionary<int, List<T>> dict, int key) {
    return dict.TryGetValue(key, out var output) ? output : new List<T>();
 }
 }

Upvotes: 2

tvdias
tvdias

Reputation: 840

Extension methods must be accessible by the caller and in a static class.

public static class Extensions
{
    public static List<T> TryGet<T>(this Dictionary<int, List<T>> dict, int key) {
        return dict.TryGetValue(key, out var output) ? output : new List<T>();
    }
}

Upvotes: 2

Related Questions