I have a fluent validator:
RuleFor(x => x.TypeTest)
.NotEmpty()
.WithMessage(x => string.Format(MessagesValidation.ValeurRequise, nameof(x.TypeTest)))
TypeTest is enum type
public enum TypeTest
{
A,
B,
C,
}
Even I give TypeTest = "A" validator doesn't valid it and return an error.
Solution but I didnt Like it:
public enum TypeTest
{
Empty = 0,
A,
B,
C,
}
is there any other solution ? please.
Updated
the problem is anytime I give the first value, it consider as Empty, and validator return an error. that is why I add a new value as Empty but im asking if there's an other way ?
Why are you trying to validate an enum type using NotEmpty() method? Enum can never be empty. It always has a default value.
If you want to validate value of an enum type, you should use IsInEnum() method.
Also, you can't assign a string to an enum type as you've written in your question.
If you want TypeTest to allow for "empty" values, make the property nullable:
public TypeTest? TypeTest { get; set; }
// ^ (the question mark after the type allows nulls to be assigned)
That should get the "NotEmpty()" validator working, but the downside is introducing an additional possible value for an enum: null. Depending on your use case, a null value might be desirable. Changing the type of the property from TypeTest to TypeTest? will require downstream code changes. Anything relying on the TypeTest property will need to access the enum value using x.TypeTest.Value rather than just x.TypeTest.
Related
In class Microsoft.Net.Http.Headers.ContentRangeHeaderValue, there is a nullable value type property (long?) that is decorated with a NotNullIfNotNull attribute referencing itself (property Length).
[NotNullIfNotNull(nameof(Length))]
public long? Length { get; private set; }
What is the purpose of this attribute in the context of a value type and what is the difference to simply omitting the attribute declaration?
According to the definition: A return value, property, or argument isn't null if the argument for the specified parameter isn't null.
The use-case scenario:
Sometimes the null state of a return value depends on the null state of one or more arguments. These methods will return a non-null value whenever certain arguments aren't null. To correctly annotate these methods, you use the NotNullIfNotNull attribute.
Examples or code snippets can be found here.
I think I slowly get an idea what problem this declaration attempts to solve:
The property could write the value it receives to a different variable than the one that is returned (using a property like this)
[NotNullIfNotNull(nameof(Length))]
public long? Length {
get { return _length }
private set { _anotherLength = value }
}
or simply ignore the value in the setter or do some other strange things, the attribute is needed to tell the analyzer the value given to the setter does indeed set the variable returned in the getter.
Intention :
I am writing a business application that uses multiple enums where most of these enums exists in tables in the database too. The problem comes in maintenance when one of the team members or a late developer changes an enum member value at one of the two places leaving the enum unsynced. To solve this problem I am trying to create a custom enum attribute that throws some exception when it finds that an enum values are not in sync.
Implementation :
[AttributeUsage(AttributeTargets.Enum)]
public class EnumSyncAtrribute : Attribute
{
public EnumSyncAtrribute(Type databaseAccessType, Type enumType))
{
// Code that uses that databaseAccessType to access the database to get
// enum values then compare it to values of enumType , goes here.
}
}
Then target enum is marked as follows
[EnumSyncAtrribute(typeof(MyDataBaseAccess), typeof(MyEnum))]
public enum MyEnum
{
value1 = 0,
value2 = 1,
value3 = 2
}
Problem :
The problem is this attribute constructor never executes! I have tried replacing Enums with Classes and found that it executes fine, but with Enums, no!
The question is, when custom attributes are used for enums, when does their constructors executes?
The attribute is constructed only when you retrieve it (using the GetCustomAttribute function). Otherwise, its construction recipe (constructor overload + positional parameters + properties values) is only stored in the assembly metadata.
In your case, I'd retieve all enum types from the assembly, and check if they have the attribute. Something like that at the startup of your application:
var allEnumTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => t.IsEnum);
foreach(var enumType in allEnumTypes)
{
var syncAttr = Attribute.GetCustomAttribute(enumType, typeof(EnumSyncAtrribute)) as EnumSyncAtrribute;
if (syncAttr != null)
{
// Possibly do something here, but the constructor was already executed at this point.
}
}
I have this extension method for an Enum:
public static List<Enum> Values(this Enum theEnum)
{
return Enum.GetValues(theEnum.GetType()).Cast<Enum>().ToList();
}
I'm getting a code analysis violation:
CA1062 Validate arguments of public methods
In externally visible
method 'EnumExtensions.Values(this Enum)', validate parameter
'theEnum' before using it.
Why is that happening? How can I validate the parameter? I can't check for null because an enum is a non-nullable value type. Is there some other check that is supposed to be occurring here?
I can't check for null because an enum is a non-nullable value type.
Any particular enum is a value type, but Enum itself isn't. (Just like ValueType isn't a value type either... every type derived from ValueType except Enum is a value type.)
In other words, I could write:
Enum foo = null;
var bang = foo.GetValues();
That would compile and then fail at execution time with a NullReferenceException.
Given that you ignore the value except to get its type, I'd actually suggest removing it and either accepting a Type or making it generic in the type of enum you want. But if you want to keep the current signature, you just need:
if (theEnum == null)
{
throw new ArgumentNullException();
}
You might also want to look at my Unconstrained Melody project which provides a bunch of helper methods for enums, generically constrained to enum types via IL manipulation.
The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.
It is used just for declare another enums. In any case, the input should be your declaration.
public enum theEnum {
enum1,
enum2
}
public void ShowEnum(theEnum e)
{
System.Console.WriteLine(e.GetType());
}
I've got a custom attribute that I want to apply to an enum type itself, but I'm having trouble identifying the correct path to get at the proper *Info in order to expose the attribute.
Something like this
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class MyCustAttribute : Attribute {}
[MyCust()]
[MyCust()]
[MyCust()]/*...and so on...*/
public enum MyEnumType{}
I am familiar with the more "customary" methods of reflecting say a DescriptionAttribute from an enumerated value. I do that sort of thing all the time, no problem. As in the following type case.
public enum MyEnumType {
[Description("My First Value")]
First,
[Description("My Second Value")]
Second,
}
I'm sure it's obvious, but I fail to see whether this is possible.
You can iterate over your custom attributes of an enum type like this:
static void Main(string[] args)
{
var attributes = typeof(MyEnumType).GetCustomAttributes(typeof(MyCustAttribute), false);
foreach (MyCustAttribute attribute in attributes)
Console.WriteLine("attribute: {0}", attribute.GetType().Name);
Console.ReadKey();
}
In this example, GetCustomAttributes returns an array of object. We use the ability of a foreach loop to cast up to the type we know the array elements contain because that's what we asked for: MyCustAttribute.
Since your custom attribute doesn't have anything interesting in it yet, we just chose to print out the name of the type. You'll obviously do something more exciting with your real instance of the type.
Enums are generally used to define the state of a particular property of a class, say in an object model of some sort. For some of these properties, the state 'this property is not set' is valid.
In these situations, should I use a zero None enum value, or make the property type nullable?
public MyEnum Property { get; set; }
public enum MyEnum {
None = 0,
Value1,
Value2
}
or
public MyEnum? Property { get; set; }
public enum MyEnum {
Value1,
Value2
}
Use MyEnum.None - it is much more expressive, or even MyEnum.Invalid to convey meaning.
You can also set it to other values than 0 - since it is based on int, you can set it to be -1 and the first valid value to 1:
public enum MyEnum {
InvalidValue = -1,
Value1 = 1,
Value2
}
In your code you can easily check for this value being passed in and throw a descriptive exception.
A nullable enum type is not expected and less expressive. It requires users of you code to be aware of this and check for nulls.
It's hard to answer this conclusively, a lot of factors in your app will influence this. I tend to just define the enum value to 0, but not specify a zero value in the enum.
enum Foo
{
A = 1,
B = 2
}
...
Foo myFoo = (Foo)0;
This gives the benefit of a sentinel value, without polluting the enum.
I would use the "None" value instead of a nullable enum. If nothing else, to me if(Property == MyEnum.None) is a lot more readable than if(Property == null).
Another option is to set the first value to 1, since it will be initally 0.
public enum MyEnum {
Value1 = 1,
Value2
}
I think both of your situations are acceptable! It will depend upon your situation. When working with a user interface your first example with the 'None' value will probbaly be easier to use. However, the Nullable gives more information about how the variable should be used.