0

Is there a way to get string.Format to always return an empty string?

    string.Format("", DateTime.Now);  

3rd party component lets us pass no more than a format string. The empty string idea doesn't work. Was hoping there might be another less obvious way. I do not deny that the below code works (answers), it is just that I can't reprogram said 3rd party component.

5
  • 3
    Why would you want to do this? Why not just String.Empty? Commented Sep 28, 2012 at 0:24
  • The code shown should do as much... Commented Sep 28, 2012 at 0:31
  • @KyleC: see amended question above Commented Sep 28, 2012 at 0:38
  • 1
    @sgtz Why doesn't empty string format work? And can you specify different formats for different arrg list? Commented Sep 28, 2012 at 0:43
  • @KonstantinVasilcov: there must be some hand coded logic by the 3rd party (like string.EmptyOrNull) that sets it to a default. Possibly I'm asking the impossible from this angle and need to look at an IValueConverter Commented Sep 28, 2012 at 9:21

3 Answers 3

3

string.Format("{0}", string.Empty)?

Sign up to request clarification or add additional context in comments.

2 Comments

I should say that date will always have a valid date in it... and that all that I can do is pass a 3rd party library is the format string. I'm trying to trick it.
Your example should work just fine: string.Format("", DateTime.Now) - I just checked in a simple Console App and it resulted in a blank string.
2

How about

string.Format(string.Empty, other, useless, parameters);

2 Comments

Wokay, but how is this essentially different from the OP's code...?
@sehe For a task this simple, it is hard to come up with anything different, let alone essentially different. The only difference is referencing string.Empty explicitly, and the OP requested a return of string.Empty.
1

The answer is:

string.Format(" ", DateTime.Now);

At least that's the way to trick the 3rd party software into giving the desired result.

1 Comment

Although the empty format string in a string.Format does format a value as blank, how it works in practice will depend on any application code that consumes the format string before passing it to a string.Format. Ignoring a null/blank format string is a reasonable action, hence a single space working for you. This trick works in ASP.Net MVC HTML Helpers too, i.e. if you want the benefits of using a TextBoxFor but don't want to render the value then a " " format string will blank the value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.