Page 2 of 2
Posted: Thu 14 Jun, 2007 3:27 pm
by benryves
King Harold wrote:What can C# not do?
At a syntactic sugar level, it's missing something like VB's With keyword. For example,
Code: Select all
With SomeButton
.Text = "Hello"
.Width = 100
.Height = 30
End With
C#3 remedies this somewhat with object initialisers.
More seriously, C# is lacking filtered exception handling. For example,
Code: Select all
Try
' ...
Catch ExA As Exception When <boolean conditional>
' For example, you could check to see if you can recover from the
' exception and try again.
Catch ExB As Exception
' Otherwise...
End Try
(This is a CLR feature).
Also, in C# you need to manually attach event handlers. In VB, you can declare a method as an event handler using the Handles keyword.
Posted: Thu 14 Jun, 2007 3:58 pm
by King Harold
Ok I see, you can catch(TypeOfError name) though
Posted: Thu 14 Jun, 2007 4:31 pm
by benryves
King Harold wrote:Ok I see, you can catch(TypeOfError name) though
That's not quite the same. VB lets you catch exceptions based on their type too, but also lets you catch exceptions of a particular type along with a particular condition (for example, you could catch FileNotFoundException twice, handling it one way for files on fixed disks and another way for removable media). Yes, you could do this by having a conditional inside the catch block, but as it's a feature of the CLR it would be nice to have native support for it (not to mention it gives cleaner code).
Here's a
nice example I found:
Code: Select all
Public Class CalcException
Inherits ApplicationException
Public Sub New()
End Sub
Public Sub New(ByVal Message As String)
MyBase.New(Message)
End Sub
Public Sub New(ByVal Message As String, ByVal Inner As Exception)
MyBase.New(Message, Inner)
End Sub
Public Function IsRecoverable() As Boolean
If Rnd() > 0.5 Then IsRecoverable = True
End Function
End Class
Code: Select all
Option Explicit On
Option Strict On
' Structured Exception Handling (SEH) Sample
' User-Filtered Exceptions
Module Filtering
Sub Main()
Dim I As Byte
For I = 1 To 5
Try
' Mess things up (Big Bad Bug)
Throw New CalcException("A Big Bad Bug crashed the code.")
Catch ExCalc As CalcException When ExCalc.IsRecoverable
Console.WriteLine(ExCalc.Message)
Console.WriteLine("Mini boom! (Recovered fine.)" & vbCrLf)
Catch Ex As Exception
' Well, turns out it was not recoverable after all
Console.WriteLine(Ex.Message)
Console.WriteLine("Kaboom! (Not recovered.)" & vbCrLf)
End Try
Next
Console.ReadLine()
End Sub
End Module
There are of course ways around this sort of thing. VB doesn't support unsafe code, but you can still read/write to unmanaged memory (for example) using Marshal.Copy.
Posted: Thu 14 Jun, 2007 8:21 pm
by King Harold
Ok that does look useful, any chance it's going to be added to C#?