TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Generic Method

This C# example program shows how to create generic methods and call them.

Generic methods have type parameters.

They provide a way to parameterize the types used in a method. This means you can provide only one implementation and call it with different types. Generic methods require an unusual syntax form.

Generic Class

Note: The syntax form for the declaration uses the <T> characters after the method name but before the formal parameter list.

Example. This program demonstrates the use of a generic method in the C# language. Generic methods use at least one explicit type parameter, which is customarily the type T or V or TValue or similar.

Also: This type is an open type. It is not precisely described in the program. Few assumptions about its representation can be made.

C# program that declares generic method

using System;
using System.Collections.Generic;

class Program
{
    static List<T> GetInitializedList<T>(T value, int count)
    {
	// This generic method returns a List with ten elements initialized.
	// ... It uses a type parameter.
	// ... It uses the "open type" T.
	List<T> list = new List<T>();
	for (int i = 0; i < count; i++)
	{
	    list.Add(value);
	}
	return list;
    }

    static void Main()
    {
	// Use the generic method.
	// ... Specifying the type parameter is optional here.
	// ... Then print the results.
	List<bool> list1 = GetInitializedList(true, 5);
	List<string> list2 = GetInitializedList<string>("Perls", 3);
	foreach (bool value in list1)
	{
	    Console.WriteLine(value);
	}
	foreach (string value in list2)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

True
True
True
True
True
Perls
Perls
Perls

This program uses a generic method to construct a List with a certain number of elements of a certain type and with a specific initial value. The GetInitializedList member is the generic method and it uses a type parameter with name T.

List Examples

Note: The first parameter to the GetInitializedList method is also a value of type T.

And: When you specify the type parameter, you can access the type parameter from other parts of the method signature as shown.

Finally, the program proves the correctness of the logic in the GetInitializedList method. It prints the values of a five-element List of Booleans, and the values of the three-element List of strings.

Console.WriteLineBool Type: If True, FalseString Type

And: Each of those values has the value we specified in the two method invocations to the GetInitializedList call.

Discussion. Let's examine the C# language specification's description of type parameters in classes and methods. The specification describes in precise detail all of the results for computing type inference matches.

Also: It describes the algorithm used by the language compiler. But these details are not useful for most programs.

Tip: Do not rely on language specification details in your program. Most developers do not study language specifications at length.

Disambiguation. Much complexity in generic methods involves disambiguation, the process by which the exact method you want to invoke is searched for and selected. This is also referred to as part of method overload resolution.

Overload Method

Note: You can often omit the type parameter, but not where the method call cannot be determined from the context.

In C# programming, many methods are generic methods. Array.Resize and Array.IndexOf are generic methods. This provides them with a performance boost over a version that uses explicit casting, and possibly improved reliability.

Note: Please see the Array.Resize article for another syntax example. Array.IndexOf is also described.

Array.ResizeArray.IndexOf

Summary. We examined generic methods and how they can be declared and invoked. Further, we touched on the concept of open types and type parameters and their syntax forms. We noted the problems of disambiguation and type inference.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf