Javascript's void in C#?
Is there something like Javascript's void
operator in C#?
void
, "evaluates an expression and discards the result, returning undefined
". Thus, I'm looking for something built-in that "evaluates" and returns null
, or maybe the type default. (So it should sort of be like the inverse of the null-coalescing ??
operator.)
Example use:
Person a;
public void main() {
var x = void(a = new Person());
// x should contain null
}
class Person { }
(Example does not compile due to illegitimate use of keyword "void", naturally.)
I currently use this—which works—but feels crufty:
protected object voided(object ob) {
return null;
}
Edit. Ok, so I definitely need to add some more details. I'm using the code in an inline DataBind expression in ASP.NET code. E.g.:
<开发者_如何学Go;asp:Repeater runat="server">
<ItemTemplate>
</tr><%# voided(globalPersonVariable = (Person)Container.DataItem)) %></tr>
</ItemTemplate>
</asp:Repeater>
Using default
, unfortunately does not work here.
Something like this you're looking for?
var x = default(Person) // null
var i = default(int) // 0
You could just make an extension method, Voided()
public static object Voided<TType>(this TType tThis)
{
return null;
}
Then you can call it like so:
(globalPersonVariable = (Person)Container.DataItem)).Voided()
If you want to combine this with the default stuff other people have mentioned, it would change to:
public static TType Voided<TType>(this TType tThis)
{
return default(TType);
}
Not sure what void
function does in javascript, but to get a default value of a type, use default
keyword:
protected T voided<T>(T obj) {
return default(T);
}
You could use the default
keyword:
http://msdn.microsoft.com/en-us/library/xwth0h0d(v=vs.80).aspx
I just want to throw these two snippets into the mix. Both work, but they still feel more verbose than necessary.
(globalPersonVariable = (Person)(Container.DataItem)) == null ? null : null
((Func<object,object>)(x => null))(globalPersonVariable = (Person)(Container.DataItem))
For databinding purposes, you can also emit the empty string:
(globalPersonVariable = (Person)(Container.DataItem)) == null ? "" : ""
The distinction might seem trivial, but this can save you from needing to cast the nulls in certain situations.
精彩评论