Home >Backend Development >C++ >How to Add Validation Attributes to Runtime Properties in C#?

How to Add Validation Attributes to Runtime Properties in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-03 15:58:39505browse

How to Add Validation Attributes to Runtime Properties in C#?

Adding Attributes to Runtime Properties

In your attempt to add a validation attribute to a property at runtime, you've encountered an exception stating "Collection was of a fixed size." To resolve this issue, consider the following:

The code you've provided involves invoking the FillAttributes method. This particular method, however, expects an array of attributes as its argument, not a single attribute. To rectify this, you should modify your code to pass an array containing the desired attribute:

// Create an array of attributes
var attributes = new ValidationAttribute[] { attribute };

// Invoke FillAttribute method
methodInfo.Invoke(propDesc, new object[] { attributes });

Alternatively, you could bypass the FillAttributes method entirely and directly assign the attribute to the property descriptor:

// Assign attribute to property descriptor
propDesc.Attributes = new Attribute[] { new RequiredAttribute() };

Depending on the specific scenario and your design preferences, entweder of these approaches should allow you to add attributes to properties at runtime without encountering the "Collection was of a fixed size" exception.

The above is the detailed content of How to Add Validation Attributes to Runtime Properties in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn