There are this, this and this questions about Enum VS Property name conflicts.
My question is not about the naming conventions, instead I’d like to know how to solve the name conflict demonstrated in the code below:
namespace Test
{
public class Person
{
// 1)
// Gender? Gender { get; set; }
// 2)
Gender Gender { get; set; }
public Person ()
{
// 1 - Error CS1061: Type `Test.Gender?' does not contain a definition for `Male' and no extension method `Male' of type `Test.Gender?' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Test)
// 2 - OK
Gender = Gender.Male;
}
}
public enum Gender
{
Male = 1,
Female
}
}
If I declare the property as in 2) Gender Gender { get; set; } the code compiles successfully, however, if I declare as in 1) Gender? Gender { get; set; } (commented in the code above) i get the error
Error CS1061: Type `Test.Gender?' does not contain a definition for `Male' and no extension method `Male' of type `Test.Gender?' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Test)
Why does it happen ?
Gender?meansNullable<Gender>, this means that when you writeGender.Malethe compiler thinks you are trying to invoke a getter on a property calledMaleon theNullable<Gender>instance, i.e.Genderis interpretted as a read of thethis.Genderproperty andMaleas the read of a property calledMaleupon the result of that.The compiler does not identify case (2) as an error as enums cannot have methods so the only resolution that makes sense is for the symbol is the enum itself.
You can fix this by increasing the name qualification: