Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to pass null arguments to a method in C#

2 Answers

0 votes
using System;
 
public class Program
{
    private static void Method(int? arg) {
        if (arg.HasValue) {
            Console.WriteLine("arg HasValue = " + arg);
        }
     
        arg = null; 
        Console.WriteLine("arg = " + arg);
        Console.WriteLine("arg = " + arg.HasValue);
         
        arg = 2983; 
        Console.WriteLine("arg = " + arg.Value);
    }
     
    public static void Main(string[] args)
    {
        Console.WriteLine("Example 1:");
        int val1 = 100;
        Method(val1);
         
        Console.WriteLine("\nExample 2:");
        int? val2 = null;
        Method(val2);
        
        Console.WriteLine("\nExample 3:");
        Nullable<int> val3 = null;
        Method(val3);
    }
}
  
  
  
/*
run:
    
Example 1:
arg HasValue = 100
arg = 
arg = False
arg = 2983

Example 2:
arg = 
arg = False
arg = 2983

Example 3:
arg = 
arg = False
arg = 2983
    
*/

 



answered Jun 22, 2024 by avibootz
edited Jun 22, 2024 by avibootz
0 votes
using System;
 
public class Program
{
    private static void Method(Nullable<int> arg) {
        if (arg.HasValue) {
            Console.WriteLine("arg HasValue = " + arg);
        }
     
        arg = null; 
        Console.WriteLine("arg = " + arg);
        // Console.WriteLine("arg = " + arg.Value); // ERROR
         
        arg = 10923; 
        Console.WriteLine("arg = " + arg.Value);
    }
     
    public static void Main(string[] args)
    {
        Console.WriteLine("Example 1:");
        int val1 = 228;
        Method(val1);
         
        Console.WriteLine("\nExample 2:");
        int? val2 = null;
        Method(val2);
        
        Console.WriteLine("\nExample 3:");
        Nullable<int> val3 = null;
        Method(val3);
    }
}
  
  
  
/*
run:
    
Example 1:
arg HasValue = 228
arg = 
arg = 10923

Example 2:
arg = 
arg = 10923

Example 3:
arg = 
arg = 10923
    
*/

 



answered Jun 22, 2024 by avibootz
edited Jun 22, 2024 by avibootz

Related questions

...