Nagaraj Tantri
Nagaraj Tantri

Reputation: 5242

string ToUpper() function with ToString()

I have used a string in C# where i am using C# in Visual studio 2008. I wanted to convert it to uppercase.

string lowerString = txtCheck.Text;
string upperString = lowerString.ToUpper();

Normally this is how i should have used, But the thing is i didn't get any error when i used it like this

string upperString = lowerString.ToUpper().Tostring();

Now i am confused that ToUpper() is also a function, then how can i use the second syntax where i again use ToUpper().Tostring(); . I mean It would mean Function1().Function2().

Upvotes: 5

Views: 57221

Answers (3)

paxdiablo
paxdiablo

Reputation: 881563

Think of it as:

string upperString = (lowerString   .ToUpper())   .ToString();

In other words, the thing that get returned from lowerString.ToUpper() is having ToString() applied to it. That's redundant since it's already a string but it's by no means an error.

It's no different to some other languages where the equivalent would be:

upperString = toString (toUpper (lowerString));

In fact you can do all sorts of weird things like:

string upper = lower.ToUpper().ToLower().ToUpper().ToString().ToString();

although that monstrosity should never get past a code review :-)

Upvotes: 3

ToUpper() is a function that takes a string and returns another string, so you're OK just doing:

string upperString = txtCheck.Text.ToUpper();

No need to call ToString() at all.

Upvotes: 6

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

No, you're calling ToString on the object returned by ToUpper. This is pointless, but it's not a compilation error. If you did:

lowerString.ToUpper.ToString();

that will indeed give you an error, since you can't call a method (ToString) on a method group.

Upvotes: 10

Related Questions