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
}
}
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.
The OP's question is answered well already, but the title is just broad enough that I think it benefits from the following primer:
output:
You can use NullableValueTypes (like int?) for this. The code would be like this:
Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?
e.g.
I think the nearest C# equivalent to
int*
would beref int?
. Becauseref int?
allows the called method to pass a value back to the calling method.int*
ref int?
From C# 2.0: