Sir Maxwell Sir Maxwell - 2 months ago 6x
C# Question

C# passing an optional parameter of type object

I got this code here that takes a string parameter:

public static void DisplayText(string Default)
foreach (char c in Default)

Now, what I need is to be able to make this code works so it can also take multiple parameters:

DisplayText("Welcome to you, {0} the {1}.", player.Name, player.Class);

But I also need to be able to only put a string parameter with nullable object parameters. I tried this code here:

I tried using the nullable<> but It got me nowhere.

Now, any pointers?


Why not use String.Format() with your input.

So call:

DisplayText(String.Format("Welcome to you, {0} the {1}.", player.Name, player.Class));

String.Format() takes a string plus an array (params) of other strings, that are assigned to the {0} and {1} locations.


string str = String.Format("Welcome to you, {0} the {1}.", player.Name, player.Class);
//str = "Welcome to you, bob the greatest"

Failing that, you will need to create an overloaded DisplayText() method with your requirements.

Something like:

 private static void DisplayText(string message, params string[] otherStrings)
   // otherStrings will be null or contain an array of passed-in-strings        

Doing the overload method will give you 2 options in your intellisense when you type DisplayText(); one for each of the signatures.