TheDeveloperBlog.com

Home | Contact Us

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

<< Back to C-SHARP

C# typeof and nameof Operators

Use the typeof and nameof operators to get the type data of objects. Evaluate typeof performance.
Typeof returns Type objects. It is often used as a parameter or as a variable or field. The typeof operator is part of an expression that acquires the Type pointer.Type
Nameof, meanwhile, returns a string with a variable's name. It works at compile-time. It is a special compiler feature that simplifies some programs.
Typeof example. Here we use typeof in a simple program. The types the program uses are found in the System namespace and the System.IO namespace.

Metadata: The typeof operator uses reflection to access the metadata descriptions of the types.

Type: We display the string representation of these Type pointers. We assign the result of the typeof operator to a Type variable or field.

Console

ToString: This program calls ToString on the Type pointers—this returns a string representation of the type.

C# program that uses typeof expressions using System; using System.IO; class Program { static Type _type = typeof(char); // Store Type as field. static void Main() { Console.WriteLine(_type); // Value type pointer Console.WriteLine(typeof(int)); // Value type Console.WriteLine(typeof(byte)); // Value type Console.WriteLine(typeof(Stream)); // Class type Console.WriteLine(typeof(TextWriter)); // Class type Console.WriteLine(typeof(Array)); // Class type Console.WriteLine(typeof(int[])); // Array reference type } } Output System.Char System.Int32 System.Byte System.IO.Stream System.IO.TextWriter System.Array System.Int32[]
Nameof example. The nameof keyword returns a string containing the identifier of a variable. This is a compile-time feature. The compiler knows the names of variables, and it inserts them.

So: We can use nameof even on local variables. We use it here to get an argument's name (size) and a local's name (animal).

C# program that uses nameof using System; class Program { static void Test(int size) { // ... Write argument name with nameof. Console.WriteLine(nameof(size)); Console.WriteLine(size); // ... Use nameof on a local variable. var animal = "cat"; Console.WriteLine(nameof(animal)); } static void Main() { // Call method. Test(100); } } Output size 100 animal
Typeof performance. Typeof uses a simple (and fast) form of reflection on the type pointer. Reflection usually will slow down a program. In critical loops, this may be a problem.

Info: We can store the results of the typeof expression. We can use this static Type field wherever we require the Type pointer.

Version 1: This code uses the typeof operator. If this returns null, the program is exited.

Version 2: This version of the code uses a cached static Type pointer. The same if-check is done in this loop as in version 1.

C# program that optimizes typeof using System; using System.Diagnostics; class Program { static Type _type = typeof(Stopwatch); const int _max = 100000000; static void Main() { var s1 = Stopwatch.StartNew(); // Version 1: use typeof. for (int i = 0; i < _max; i++) { Type type = typeof(Stopwatch); if (type == null) { throw new Exception(); } } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use static type cache. for (int i = 0; i < _max; i++) { Type type = _type; if (type == null) { throw new Exception(); } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } } Output 1.64 ns typeof expression 1.37 ns static type
Performance results. Evaluating typeof on a class in a tight loop required more time than a static Type pointer. Even in 2019, there is an advantage to the cached pointer.Benchmark

Info: The .NET Framework has optimizations to compare multiple typeof expressions. This optimization is not always useful.

Typeof uses. Some common uses of the typeof operator are the Enum static methods, the DataTable class and similar classes, and the ArrayList conversion methods.Enum.GetNameEnum.ParseDataTableConvert ArrayList, Array
Notes, metadata. Type pointers are returned when the typeof(T) expressions are evaluated. The metadata in .NET is a relational database that contains many tables for types in C# programs.

Tip: The lowercase types such as "char" and "int" are aliased to the framework types "System.Char" and "System.Int32" in mscorlib.dll.

Using System
A summary. Typeof is an operator. We assigned the result of typeof expressions to a Type field or variable. There are many common uses of the typeof operator in the .NET Framework.
With nameof, we access a string that indicates a variable's name. Instead of a Type, it returns a string name. This is also helpful in many programs.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


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