-6

How to create a method with overloading concept without changing the constructor?

I want to use a thread with parameters, but im not sure if I need to put pratameters because some time it's not necessary for me to let the method take parameters. Again is there away to create a method with parameters but its not obligatory to give parameters, I don't want to use overloading concept.

public void DoIt(string text){
//do something with text //do other things
}

DoIt(); //the method will do other things without paying attention to do something with text
Julián Urbano
  • 8,378
  • 1
  • 30
  • 52
  • 2
    Why don't you want to use overloading? – GrandMasterFlush Apr 03 '13 at 13:36
  • 2
    Your question makes almost no sense. A constructor has to do with the creation of an instance of a class, not necessarily with a method. – tnw Apr 03 '13 at 13:36
  • That's not clear, can you put more code and an example of usage? – Thomas Apr 03 '13 at 13:37
  • 2
    Check out optional parameters. The accepted answer on this question should help: http://stackoverflow.com/questions/3316402/method-overloading-vs-optional-parameter-in-c-sharp-4-0 – ametren Apr 03 '13 at 13:38
  • @MostafaSarsour You don't need overloading here, the optional parameters were made right for such cases – Alex Apr 03 '13 at 13:45

3 Answers3

3

Sure, overload it, and have your fullest method handle parameters or none, and your overloads call that one with appropriate parameters (if they are similar enough in function, which they most definitely should be - otherwise call the new method something entirely different, indicative of that):

public void DoIt(string text) {
  if (!string.IsNullOrEmpty(text)) {

  } else {

  }
} 

public void DoIt() {
  DoIt(""); // or DoIt(null);
}

You can also use optional parameters in later C# versions, but this isn't overloading: it will let you specify a default value for the parameter arguments and then omit such parameters in the call. This, however, isn't overloading, and you're constrained to making sure all optional parameters are trailing parameters of the signature.

I'm not sure where you think the constructor comes into this, though.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
2

You can use default paramenters

public void DoIt(string text="")

By doing this you can call DoIt() when you don't want to use parameter or DoIt("someString") when you want to pass something there

Alex
  • 8,827
  • 3
  • 42
  • 58
1

In c# 4 and above you can specify default values for parameters, so it's not necessary to specify them at the call site:

public void DoIt(string text = "")
{
   //do something with text 
   //do other things
}

and then you can call it either passing a parameter, like this:

DoIt("parameterValue");

or without passing a parameter, in which case, the value specified in the method definition will be used:

DoIt(); // equivalent to DoIt("");
SWeko
  • 30,434
  • 10
  • 71
  • 106