Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing null arguments to C# methods

Tags:

methods

c#

null

Is there a way to pass null arguments to C# methods (something like null arguments in c++)?

For example:

Is it possible to translate the following c++ function to C# method:

private void Example(int* arg1, int* arg2) {     if(arg1 == null)     {         //do something     }     if(arg2 == null)     {         //do something else     } } 
like image 753
Niko Gamulin Avatar asked Nov 07 '08 09:11

Niko Gamulin


People also ask

Can you pass null as argument in C?

You can pass NULL as a function parameter only if the specific parameter is a pointer. The only practical way is with a pointer for a parameter.

Can you use null in C?

Null is a built-in constant that has a value of zero. It is the same as the character 0 used to terminate strings in C. Null can also be the value of a pointer, which is the same as zero unless the CPU supports a special bit pattern for a null pointer.

Can we pass null parameter in function?

Short answer is YES, you can use null as parameter of your function as it's one of JS primitive values.

How do you declare null in C?

In practice, NULL is a constant equivalent to 0 , or "\0" . This is why you can set a string to NULL using: char *a_string = '\0'; Download my free C Handbook!


1 Answers

Yes. There are two kinds of types in .NET: reference types and value types.

References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference.

Value types (e.g. int) by default do not have a concept of null. However, there is a wrapper for them called Nullable. This enables you to encapsulate the non-nullable value type and include null information.

The usage is slightly different, though.

// Both of these types mean the same thing, the ? is just C# shorthand. private void Example(int? arg1, Nullable<int> arg2) {     if (arg1.HasValue)         DoSomething();      arg1 = null; // Valid.     arg1 = 123;  // Also valid.      DoSomethingWithInt(arg1); // NOT valid!     DoSomethingWithInt(arg1.Value); // Valid. } 
like image 134
Sander Avatar answered Sep 30 '22 19:09

Sander