Click here to Skip to main content
11,712,727 members (80,498 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0
I'm fond of the new .NET 4.0 optional parameters feature, but I've recently came across a limitation I do not understand.

Consider the following simple attribute:
class SomeAttribute : Attribute
{
	public SomeAttribute(string someString = null)
	{
	}
}

When I try to use the attribute in the statement [SomeAttribute()], the following error is generated on compiling:

"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type."

This strikes me as odd, since the default argument IS a constant expression.... And even stranger is the following:
The code can compile when I change null to "", or when I remove the part : Attribute
, and call for instance new SomeAttribute(). I'm clueless....

Can someone explain me why this error is generated and not in the other case?
And are there any workarounds, besides creating all sorts of constructor overload(like in .NET versions before 4.0)?
Posted 12-Jul-10 7:21am
Edited 12-Jul-10 7:43am
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Looks like a compiler bug to me, and worth reporting on Connect. Meanwhile, here's a workaround:

class SomeAttribute : Attribute
{
    public const string pnull = null;
 
    public SomeAttribute(string someString = pnull)
    {
    }
}
 
[SomeAttribute()]
class App
{
    static void Main()
    {
    }
}
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 CHill60 335
1 Sergey Alexandrovich Kryukov 300
2 OriginalGriff 230
3 Andy Lanng 160
4 Maciej Los 130
0 CHill60 335
1 Sergey Alexandrovich Kryukov 300
2 OriginalGriff 230
3 Andy Lanng 160
4 Maciej Los 130


Advertise | Privacy | Mobile
Web02 | 2.8.150819.1 | Last Updated 12 Jul 2010
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100