views:

558

answers:

2

I'm just curious why class/property attributes in VB.NET have a weird optional syntax such as:

<TestAttr("a", "abc", Optional1:="foo", Optional2:=3)>

VB.NET allows you to set optional parameters like this to avoid order restrictions (which is lovely) but in this case it's forcing you to that.

For example this is not possible:

<TestAttr("a", "abc", "foo", 3)>

even though the parameters are in the same order as the original definition.

Is there any good reason for this? Or is it just .NET designers were lazy on the subject?

+3  A: 

It looks like you're confusing optional parameters with named attribute arguments here. With attributes it's legal to set public field / properties of the attribute which have no corresponding parameter in the constructor. VB.Net chose to have the same syntax as it's call by name syntax.

If you open TestAttr in reflector, I think you will find the class has a constructor which takes 2 arguments and has 2 public fields with names Optional1 and Optional2.

JaredPar
I see I never wrote an attribute, now it makes more sense. Since there is no order in public field it can't be used :) Make sense now.
dr. evil
A: 

The required parameters are constructor parameters. The optional ones are present as public writable properties. It would be necessary to create constructors that supply all parameters. It's not always worthwhile.

John Saunders