vblang
vblang copied to clipboard
I propose we add Something keyword
I propose that we add Something keyword.
We sometimes write like this:
If object Is Nothing Then
Do Someting
End if
Sometimes we write:
If object IsNot Nothing Then
Do something
End If
Sometimes we just want to check that the variable has something. It should be clearer to write:
If Object Is Something Then
Do Something
End If
I think Something would be clearer to read than using IsNot Nothing
Also clear
If TypeOf x Is Object Then
Do Something
End If
Sorry about the code.editing. first time I.am posting an issue. Still trying to master how to format clean and easily readable code in the editor. Will do better in future posts.
@Happypig375 There's an article by Eric Lippert that there are types in .NET that don't inherit from Object, such as interfaces and open generic parameter types.
The answer, of course, is that despite the misleading use of the keyword TypeOf, we aren't checking against the type of x, we're checking if the object instance referred to by x is type-compatible with some type; and, quoting from the article:
These are all the "concrete" types; every object instance that you actually encounter in the wild will be either null, or a class, delegate, array, struct, enum or nullable value type. So it would be correct, though tautological, to say that all object instances derive from object.
so checking x against the Object type should be equivalent to testing for IsNot Nothing.
There's still unsafe pointers (from the above article), which are Something, but don't inherit from Object; the Something keyword might have value in that case. But AFAICT VB has no other syntax that relates to unsafe pointers.
Alternatively, since the TypeOf x check isn't really checking the type of x at all, the behavior of TypeOf x Is Object might return true when x is an unsafe pointer.
You can use:
If Not IsNothing(Object) Then
'Do Something
End If
IsNothing() is a legacy VB6 function, defined in Microsoft.VisualBasic.Information module. It will be easy to ask to add a new function IsSomething() to this moduleso we can write:
If IsSomething(Object) Then
'Do Something
End If
or better:
If HasValue(Object) Then
'Do Something
End If
Another way, it to just allow :
If Object Then
'Do Something
End If
This will cause an exception today, as VB tries to cast non numeric objects to boolean. Ex:
Dim o As Object = New StringBuilder()
If o Then
Console.WriteLine(o)
End If
We can give this a new meaning, to check the object is not null. but note if O contains 0, the condition will yield false! But empty strings will yield true!
So, I suggest this modification:
If o? Then
Console.WriteLine(o)
End If
The ? checks that O is not null as it used in O?.ToString()