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++ functi
You can use 2 ways: int? or Nullable, both have the same behavior. You could to make a mix without problems but is better choice one to make code cleanest.
Option 1 (With ?):
private void Example(int? arg1, int? arg2)
{
if (arg1.HasValue)
{
//do something
}
if (arg1.HasValue)
{
//do something else
}
}
Option 2 (With Nullable):
private void Example(Nullable arg1, Nullable arg2)
{
if (arg1.HasValue)
{
//do something
}
if (arg1.HasValue)
{
//do something else
}
}
From C#4.0 comes a new way to do the same with more flexibility, in this case the framework offers optional parameters with default values, of this way you can set a default value if the method is called without all parameters.
Option 3 (With default values)
private void Example(int arg1 = 0, int arg2 = 1)
{
//do something else
}