How can we return null from a generic method in C#?

CsharpServer Side ProgrammingProgramming

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

 Live Demo

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.

raja
Published on 08-Aug-2020 11:30:26
Advertisements