Click here to Skip to main content
15,887,936 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
return url.Contains('.') ? url.Substring(url.LastIndexOf('.')) : "";


I am trying to display the extension of a url given.

What I have tried:

I have used colon (:) in other programming formats but never seen one like this.
Posted
Updated 31-Mar-23 6:27am
v2
Comments
[no name] 31-Mar-23 13:12pm    
I'm guessing you wanted to return the url (instead of a substring) if it didn't contain '.'; and not simply "blank"; e.g. xxx ? yyyy : url;

It is the equivalent of the else part of an if else statement.
C#
string something;

if (url.Contains('.')) {
	something = url.Substring(url.LastIndexOf('.'))
} else {
	something = "";
}

return something;
 
Share this answer
 
v3
It's party of a conditional expression:
C#
A = B ? C : D;
If the condition B evaluates to true, then the result of the expression C is assigned to A. Otherwise, the expression D is evaluated and assigned instead.
For example:
C#
string result = x == 0 ? "Zero" : "Nonzero";
result will contain a string describing the "zeroness" of x
 
Share this answer
 
You're looking at a ternary operator. The ternary operator ?: works like a simplified If/Then/else statement.

The first part precedes the question mark, and is an expression that evaluates to true or false. In your carse, it's "url.Contains('.')". The part that immediately follows the question mark is the result if true, and the part follows the colon is the result if false.

So, in your case, "url.Substring(url.LastIndexOf('.'))" is returned is true, and "" is returned if false.

For more information on the ternary operator, have a look at this.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900