Skip to content

[API Proposal]: new TypeLocal class to get/set arbitrary values based on a supplied Generic Type #59718

@jasonswearingen

Description

@jasonswearingen

Background and motivation

You can store and retrieve Type specific values efficiently using static classes, such as:

public static class TypeStore<T>{

public static int Value;

}

thus, for a given type supplied to a Generic method you can set/get a custom value without resorting to dictionary lookups based on the Type.

This is excellent, but there is no way to do this on a per-instance basis. Doing so can greatly improve efficiency of code needing per-type values by removing a dictionary lookup each time a type is supplied.

This is a feature request for performance optimization reasons. A real-world example situation where this is helpful is in a game engine "Entity Component System" where the user (the game developer) arbitrarily wants to pick a component of type TComponent, and the game engine needs to somehow look this up in a very efficient manner, due to frame time constraints plus that this kind of lookup may be done many times during a game frame.

API Proposal

/// <summary>
/// similar to ThreadLocal, but provides a value per type.
/// </summary>
/// <typeparam name="TValue"></typeparam>
public interface TypeLocal<TValue>
{
	public TValue Get<TType>();

	public bool TryGet<TType>(out TValue value);

	public void Set<TType>(TValue value);

	public void Remove<TType>();

	public bool HasValue<TType>();

	public IEnumerator<(Type type, TValue value)> GetEnumerator();
}

API Usage

Note this is an updated example because my original example was not clear:

public class MyLookupHelper  //helper to get an array index
{
	private int indexCounter;
	private TypeLocal<int> typeLocal = new();
	public int GetIndex<T>()
	{
		if (!typeLocal.TryGet<T>(out var index){
			index = indexCounter++;
			typeLocal.Set<T>(index);
		}
		return index;
	}
}

Overall the general usage pattern would be very similar to a normal Dictionary<Type,Value>

Risks

???

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Runtimeneeds-further-triageIssue has been initially triaged, but needs deeper consideration or reconsideration

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions