locked
Question about "T" RRS feed

  • Question

  • User-284642143 posted

    So i see similar code across many searches i see. An example

            private static T GetRandomElement<T>(this IEnumerable<T> list)
            {
                var random = new Random();
    
                if (list == null)
                    throw new ArgumentNullException("list");
    
                // If there are no elements in the collection, return the default value of T
                if (list.Count() == 0)
                    return default(T);
    
                return list.ElementAt(random.Next(list.Count()));
            }

    So what does the T signify? Why T? Where could i read up on this to get a better understanding? I understand the rest of the code but i see the T is many examples and classes, I did the usual google searches but i dont think i can narrow down what im trying to ask without getting a lot of irrelevant info especially if my terminology is incorrect.

    Thanks

    Tuesday, June 25, 2019 3:27 PM

Answers

  • User475983607 posted

    Ok i would like to introduce these into my own projects, so i guess where i want to pass in my own Class/Table and "do something" common i.e. randomise the collection, move items in a collection up/down etc is where i would implement this type of logic?

    I do not understand the question.

    I recommend learning Generics which should clear up the confusion.  The constructs are covered in the C# programming guide.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 25, 2019 3:50 PM

All replies

  • User475983607 posted

    So what does the T signify?

    T signifies Type.  Meaning you can pass any type or the type is generic.

    Tuesday, June 25, 2019 3:29 PM
  • User-284642143 posted

    EssCee

    So what does the T signify?

    T signifies Type.  Meaning you can pass any type or the type is generic.

    Ok i would like to introduce these into my own projects, so i guess where i want to pass in my own Class/Table and "do something" common i.e. randomise the collection, move items in a collection up/down etc is where i would implement this type of logic?

    Tuesday, June 25, 2019 3:43 PM
  • User475983607 posted

    Ok i would like to introduce these into my own projects, so i guess where i want to pass in my own Class/Table and "do something" common i.e. randomise the collection, move items in a collection up/down etc is where i would implement this type of logic?

    I do not understand the question.

    I recommend learning Generics which should clear up the confusion.  The constructs are covered in the C# programming guide.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 25, 2019 3:50 PM