25

Duplicate Question

Passing null arguments to C# methods

Can I do this in c# for .Net 2.0?

public void myMethod(string astring, int? anint)
{
//some code in which I may have an int to work with
//or I may not...
}

If not, is there something similar I can do?

Community
  • 1
  • 1
  • I did a search and the duplicate didn't come up or that would have answered this. Thanks all. –  Mar 12 '09 at 12:25

3 Answers3

29

Yes, assuming you added the chevrons deliberately and you really meant:

public void myMethod(string astring, int? anint)

anint will now have a HasValue property.

roryf
  • 29,592
  • 16
  • 81
  • 103
21

Depends on what you want to achieve. If you want to be able to drop the anint parameter, you have to create an overload:

public void myMethod(string astring, int anint)
{
}

public void myMethod(string astring)
{
    myMethod(astring, 0); // or some other default value for anint
}

You can now do:

myMethod("boo"); // equivalent to myMethod("boo", 0);
myMethod("boo", 12);

If you want to pass a nullable int, well, see the other answers. ;)

Inferis
  • 4,582
  • 5
  • 37
  • 47
  • +1 good suggestion to use polymorphism – Dead account Mar 12 '09 at 12:21
  • 1
    @Garry, yep your right it isn't. – Dead account Mar 12 '09 at 13:03
  • 3
    I think you can avoid the overload by a definition like: `public void myMethod(string astring, int? anint = null)`. This way you can call to the method only with a string as parameter and the value of the anint variable will be null; and also call it with the string and the integer. – adripanico Sep 16 '13 at 10:31
11

In C# 2.0 you can do;

public void myMethod(string astring, int? anint)
{
   //some code in which I may have an int to work with
   //or I may not...
}

And call the method like

 myMethod("Hello", 3);
 myMethod("Hello", null);
Dead account
  • 19,587
  • 13
  • 52
  • 82