1

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?

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

it works, but now I can't success to give the value of this attribute. what sould I write to give it?
I think you need to explain in detail what you're trying to do.
I try to build an enum that the his values are not int or char. so I write before each value - [DefaultValue(Type.GetType("MyClass"),"11:00:00")] and in the ctor of the MyClass I parss the string. but now how can I recive for each value the value that I write in the DefaultValue Attribute?
In C# the enum values must be an integer type. stackoverflow.com/questions/469287/… might be helpful.
2

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

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

2 Comments

it works, but now I can't success to give the value of this attribute. what sould I write to give it?
Are you getting an error? i just read this: eggheadcafe.com/software/aspnet/32319410/… it explains a little on when the value would be visible. I must admit I have not used DefaultValueAttributes before put I might be able to help if you can give a little more detail. The other guys on this thread may be able to help also if they see this comment
1

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.

2 Comments

it works, but now I can't success to give the value of this attribute. what sould I write to give it?
I haven't used the DefaultValue attribute much, but when i did, i never needed to give it a type, i just entered some value like this for a bool: [DefaultValue(false)], since you want to use a more complex type you should look into how it tries to convert the value, maybe your class needs to implement an interface for it to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.