Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Func in C#: container factories, predicates, and selectors

Register factories with different service return types in a custom container, then use the same delegate type to filter and transform a sequence with LINQ.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

// C# 12 / .NET 8
using System;
using System.Collections.Generic;

// System.Func<T,TResult> declaration (API reference):
// public delegate TResult Func<in T, out TResult>(T arg);

// Factory registration and storage in the example's custom Container (Get omitted).
sealed class Container
{
    private readonly Dictionary<Type, Func<Container, object>> factories = new();

    public void Add<TService>(Func<Container, TService> factory) where TService : class
    {
        ArgumentNullException.ThrowIfNull(factory);
        Func<Container, object> stored = factory;
        factories.Add(typeof(TService), stored);
    }
}

// System.Linq.Enumerable extension method signatures (API reference):
// public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
// public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
// public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);
// public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector);

In C# 12 and .NET 8, System.Func<T,TResult> is a delegate that takes one argument of type T and returns a value of type TResult. In a lambda such as x => ..., => separates the parameter from the body. Assigning the lambda does not run its body; invoking f(x) does if f refers to that lambda.

The factory pair Func<Container,TService> i Func<Container,object> serves two roles: the custom Container accepts the typed factory and stores it as the object-returning delegate under typeof(TService). A factory receives the current container and can resolve dependencies from it. out TResult allows an implicit conversion to the broader reference return type object (covariance), not the reverse. in T lets a delegate accepting a broader reference type stand in for one that accepts a narrower type (contravariance); here the input stays Container. Variance does not turn a value-type result such as int into object. The example constrains TService with where TService : class; outside that constraint, a wrapper lambda such as c => intFactory(c) assigned to Func<Container,object> could box the result.

Get<TService>() invokes the factory on every call and checks the result type, rejecting null as well. A missing registration or invalid result throws InvalidOperationException, a duplicate registration throws ArgumentException, and a null factory throws ArgumentNullException. This teaching example is not the built-in .NET DI container: it has no caching, scopes, disposal, or cycle detection. Lifetime follows factory behavior and container policy, not the Func type. Register only trusted factories: a delegate runs code without sandboxing it.

The pair Func<T,bool> i Func<TSource,TResult> describes the predicate and selector roles. In System.Linq, Enumerable.Where on IEnumerable<TSource> uses Func<T,bool> with T equal to TSource: true keeps the element and false skips it. Enumerable.Select uses Func<TSource,TResult> to produce one result per input element, possibly of a different type. The indexed overloads add a second int argument: the zero-based index in that operator's own input. Execution is deferred until enumeration; a null source or delegate throws ArgumentNullException at the method call. System.Predicate<T> has the same predicate shape but is a distinct delegate type. The Queryable counterparts for IQueryable<T> take Expression<Func<...>> expression trees rather than delegate instances; expression support depends on the query provider.

Examples

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

var container = new Container();
container.Add<string>(_ => "item-");
Func<Container, Labels> makeLabels = c => new Labels(c.Get<string>());
container.Add(makeLabels);

var labels = container.Get<Labels>();
Func<int, bool> keep = n => n % 2 == 0;
Func<int, string> label = n => labels.Prefix + n.ToString(CultureInfo.InvariantCulture);

foreach (string text in new[] { 1, 2, 3, 4 }.Where(keep).Select(label))
    Console.WriteLine(text);

Console.WriteLine(object.ReferenceEquals(labels, container.Get<Labels>()) ? "same" : "different");

sealed record Labels(string Prefix);

sealed class Container
{
    private readonly Dictionary<Type, Func<Container, object>> factories = new();

    public void Add<TService>(Func<Container, TService> factory) where TService : class
    {
        ArgumentNullException.ThrowIfNull(factory);
        Func<Container, object> stored = factory;
        factories.Add(typeof(TService), stored);
    }

    public TService Get<TService>() where TService : class
    {
        if (!factories.TryGetValue(typeof(TService), out var factory))
            throw new InvalidOperationException($"No factory for {typeof(TService).Name}.");

        return factory(this) is TService service
            ? service
            : throw new InvalidOperationException($"Invalid result for {typeof(TService).Name}.");
    }
}

Result

item-2
item-4
different

The `Labels` factory resolves its prefix from the same container. `Where` keeps the even numbers, and `Select` produces `item-2` and `item-4`. The line `different` means that resolving `Labels` again returned a distinct instance.

Related lessons

  • C# · Lesson 44 · Advanced · Version: 3
  • C# · Lesson 9 · Intermediate · Version: 2

Sources