- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we return null from a generic method in C#?
Generics allows us to define a class with placeholders for the type of its fields, methods, parameters, etc. Generics replace these placeholders with some specific type at compile time. A generic can be defined using angle brackets <>. A primary limitation of collections is the absence of effective type checking. This means that you can put any object in a collection because all classes in the C# programming language extend from the object base class.
Also, we cannot simply return null from a generic method like in normal method. Below is the error that a generic method will throw if we are trying to return null.
using System; namespace DemoApplication { class Program { public static void Main() { Add(5, 5); } public static T Add<T>(T parameter1, T parameter2) { return null; } } }
So, to return a null or default value from a generic method we can make use default(). default(T) will return the default object of the type which is provided.
Example
using System; namespace DemoApplication { class Program { public static void Main() { Add(5, 5); Console.ReadLine(); } public static T Add<T>(T parameter1, T parameter2) { var defaultVal = default(T); Console.WriteLine(defaultVal); return defaultVal; } } }
Output
The output of the code is
0
Here we could see that the default value of integer 0 is returned.