Click here to Skip to main content
14,584,509 members
Rate this:
Please Sign up or sign in to vote.
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
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:

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:
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.
Rate this:
Please Sign up or sign in to vote.

Solution 1

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.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

Convert.ChangeType doesn't seem to work with enum types. You'll need to use Enum.ToObject[^] instead.
var realType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
var convertedValue = realType.IsEnum && val != null ? Enum.ToObject(realType, val) : val;
prop.SetValue(item, convertedValue, null);
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100