artlung
artlung

Reputation: 34013

?? Operator with 2 strings?

In this .NET code:

return Redirect("~/Home" ?? "JaneDoe");

If I'm reading the docs right, the "??" operator appears to operate similarly to IsNull in SQL:

IsNull("~/Home", "JaneDoe")

"~Home" and "JaneDoe" are simply strings, right? There's no condition in the return Redirect code where "JaneDoe" will be what's passed into "Redirect", is there? I'm not sure what to make of this snippet, I can only presume it's a placeholder for something to come later.

This code is from a .NET-MVC project in development, part of a .cs file that is a LoginController.

Upvotes: 3

Views: 227

Answers (5)

Kent Boogaart
Kent Boogaart

Reputation: 178660

Correct, the expression will never return "JaneDoe".

Upvotes: 1

Ta01
Ta01

Reputation: 31610

The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

In your case, it will never return JaneDoe

Upvotes: 3

user438034
user438034

Reputation:

This would always use the "~/Home" string. The null-coalescing operator (??) selects the left side if it is non-null, or the right side if it is null.

Upvotes: 1

MarkXA
MarkXA

Reputation: 4384

Yes, you're reading it correctly. That will always return "~/Home", presumably it was planned to change it to a variable at some point.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500675

Yes, this is just bad code. That will always be equivalent to

return Redirect("~/Home");

I'm slightly surprised the compiler isn't smart enough to give a warning about it, to be honest. It would be nice if it could tell that a constant non-null expression was being used on the LHS of the null-coalescing operator.

Upvotes: 7

Related Questions