TheDeveloperBlog.com

Home | Contact Us

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

C# Enumerable.Empty

This C# example program uses the Empty method on the Enumerable type. It requires System.Linq.

Enumerable.Empty generates an IEnumerable of zero elements.

It can be used when you want to avoid a query expression and instead just want to use an empty sequence. It can help when you want to return no values.

Example. As a static generic method, you must specify the type of the sequence you want to generate. Thus Enumerable.Empty(int) will return a zero-element sequence of ints (IEnumerable(int)).

Int

So: The Count() extension indicates the sequence is empty. If you use ToArray, you will get an empty array.

Count

C# program that uses Enumerable.Empty

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	var empty = Enumerable.Empty<int>();
	Console.WriteLine(empty.Count());
	int[] array = empty.ToArray();
	Console.WriteLine(array.Length);
    }
}

Output

0
0

When to use it. Enumerable.Empty helps when you want to call a method that receives an IEnumerable collection. In some calling locations, you could pass a query expression. In others, you could simply pass Enumerable.Empty.

Implementation. The implementation of Empty is interesting. It uses a static generic type and then calls a property (Instance) on that type. An empty array is lazily initialized in the Instance property.

StaticGeneric Class

Tip: Because Enumerable.Empty caches the zero-element array, it can provide a slight performance advantage in some programs.

Summary. Enumerable.Empty provides a useful bit of functionality for IEnumerable collections. With an internal element cache, it can avoid allocations. It can be used as an argument to any method that receives an IEnumerable generic type.


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