Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have enum and it's property which I want to be nullable. There are couple ways I tried to do that but I can't seem to succeed. I get "Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[Data2.Models.MyObject+TypeFlag]'." but shouldn't it allow nullable enum if I set it like this?

It breaks on
C#
prop.SetValue(item, val, null);

where prop is my nullable property, item is whole object and val is enum value (null, 1, 2 etc)

What I have tried:

C#
public enum Types: int {
  Good = 1,
    Medium = 2,
    Critical = 3,
}

[Column("types")]
[JsonProperty(PropertyName = "types")]
public Types? TypeFlag {
  get;
  set;
}


//second try 

[Column("types")]
[JsonProperty(PropertyName = "types")]
public TypeFlag ? TypeFlag {
  get {
    if (this.TypeFlag == null) {
      this.TypeFlag =
        default (TypeFlag);
    }

    return this.TypeFlag;
  }

  set {
    this.TypeFlag = value;
  }
}

I also tried changing my value setting like this:
C#
var enumType = default(T) == null && typeof(T).BaseType != null && "ValueType".Equals(typeof(T).BaseType.Name);

var convertedValue = enumType ? Convert.ChangeType(val, prop.PropertyType) : val;
prop.SetValue(item, convertedValue, null);

but it didn't help
Posted
Updated 12-Mar-20 6:34am
v4
Comments
Richard Deeming 12-Mar-20 12:22pm    
It's an ArgumentException not a NullReferenceException.

I've fixed your question title for you.

Use the "?" notation to make a non-nullable type nullable

public enum Types : int
{
    Good = 1,
    Medium = 2,
    Critical = 3,
}

public class MyData
{
    public Types? Types { get; set; }
}


Usage

var myData = new MyData();

myData.Types = null;

System.Diagnostics.Debug.WriteLine(myData.Types);

// to check if it is not null;
bool hasTypes = myData.Types.HasValue;

// or
hasTypes = myData.Types != null;

myData.Types = Types.Critical;

System.Diagnostics.Debug.WriteLine(myData.Types);


if this works for you might depend on how you are deserialising your data and what that data looks like.
 
Share this answer
 
Convert.ChangeType doesn't seem to work with enum types. You'll need to use Enum.ToObject[^] instead.
C#
var realType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
var convertedValue = realType.IsEnum && val != null ? Enum.ToObject(realType, val) : val;
prop.SetValue(item, convertedValue, null);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900