Archive for the ‘C#’ Category.

Visual Basic 10 properties still lag behind C#

Up until Visual Studio 2010, simple property definitions were always ridiculously verbose. For example:

    Private _title As String
    Public Property Title() As String
        Get
            Return _title
        End Get
        Set(ByVal value As String)
            _title = value
        End Set
    End Property

That’s 9 lines of code just to make a simple string property. Luckily, in VB 10 we will be able to write these simple properties in one line:

    Public Property Title As String

This is great, but what if things get a little more complicated? Obviously this syntax just uses the default getter and setter, both of which have the same scope. When I write my properties I like avoid using ReadOnly and instead make the setter private so that I can still encapsulate the setting code within the class. With VB 10 you still have to define the property the old way in order to do this:

    Private _title As String
    Public Property Title() As String
        Get
            Return _title
        End Get
        Private Set(ByVal value As String)
            _title = value
        End Set
    End Property

But now it’s back to 9 lines just because I wanted the setter to be private. In C#, programmers have the luxury of writing properties like this:

    public string Title { get; private set; }

Furthermore, neither language allows you to use a default getter and custom setter (or vice versa) probably because it would make it difficult for them both to use the same backing store, but that’s a whole other tangent. Overall, the new abbreviated syntax for properties in VB 10 is great for the simple cases, but you have to revert to the old, verbose method if you want to deviate from the default in even the slightest way.

LINQ to SQL Gotcha #6: Delete, Save, Insert, CRASH

If you keep the same entity around after it has been deleted and SubmitChanges() is called then you can run into an InvalidOperationException if you try to insert it again.

var data = new DataClasses1DataContext();
var user = new User() { userName = "foo", password = "bar" };
 
data.Users.InsertOnSubmit(user);
data.SubmitChanges();
 
data.Users.DeleteOnSubmit(user);
data.SubmitChanges();
 
data.Users.InsertOnSubmit(user);
data.SubmitChanges();

Here you will actually get an exception on the second InsertOnSubmit() because the data context remembered the entity and will no longer allow you to attach it for some reason. Once an entity has been deleted from a data context it can never go back. To get around this you need to either insert the entity to a different data context or copy the data to a new instance of the same entity class and then insert it. This has been confirmed here.

Note: You are free to call DeleteOnSubmit() and then InsertOnSubmit() all you want as long as you never call SubmitChanges().