© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
30 replies
Jason_Bjorn

✅ Generic function with conditional type based logic inside

How can I make something like this work? I want the user to either be able to get a list of ints or strings.

List<int> lInt = Foo<int>();
List<string> lString = Foo<string>();

// Should either returns a List of Ints or strings
List<T> Foo<T>()
{
    List<T> list = new();

    for (int i = 0; i < 10; i++)
    {
        T valueToAdd;
        if (typeof(T) == typeof(int))
        {
            valueToAdd = i;
        }
        else if (typeof(T) == typeof(string))
        {
            valueToAdd = i.ToString();
        }
        else {
            throw new InvalidOperationException($"Invalid type {typeof(T)}");
        }
        list.Add(valueToAdd);
    }
    return list;
}
List<int> lInt = Foo<int>();
List<string> lString = Foo<string>();

// Should either returns a List of Ints or strings
List<T> Foo<T>()
{
    List<T> list = new();

    for (int i = 0; i < 10; i++)
    {
        T valueToAdd;
        if (typeof(T) == typeof(int))
        {
            valueToAdd = i;
        }
        else if (typeof(T) == typeof(string))
        {
            valueToAdd = i.ToString();
        }
        else {
            throw new InvalidOperationException($"Invalid type {typeof(T)}");
        }
        list.Add(valueToAdd);
    }
    return list;
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Xml generic type deserialisation based on attribute
C#CC# / help
13mo ago
Change function behavior depending on class' generic type.
C#CC# / help
3y ago
✅ Generic nullable type
C#CC# / help
3y ago
✅ Creating a generic type based on a Type variable rather than a specific type
C#CC# / help
4y ago