RRR
RRR

Reputation: 4175

DefaultValue Attribute in C#

I want to use on DefaultValue Attribute to define default value for custom class that I write in my App. the class gives in his constractor a string. I write the follow:

[DefaultValue(Type.GetType("MyClass"),"hello world")] 

but when I try to run this App. I give error:

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

can anyone explain me what the problem?

Upvotes: 1

Views: 3404

Answers (3)

brunnerh
brunnerh

Reputation: 185290

Type.GetType() is a method (i.e. not a constant expression), as the others said, use typeof.

[DefaultValue(typeof(MyClass),"Convertible String")]

Edit: To enable the conversion of the string to your custom class you need to associate a TypeConverter with it, see the examples-section of this documentation to get an idea of how to do so.

Upvotes: 1

Peter Taylor
Peter Taylor

Reputation: 5076

You're using Type.GetType("MyClass") where you should have typeof(MyClass).

Upvotes: 6

WraithNath
WraithNath

Reputation: 18013

I suspect its the Type.GetType("MyClass");

can you try typeof(MyClass) instead, passing the type and not a string?

Upvotes: 2

Related Questions