Home > front end >  How to know if method argument is a nullable type
How to know if method argument is a nullable type

Time:01-28

I have a method which receives a dictionary of string and object

private void MyFunc(Dictionary<string, object> parameters)
{
}

I have a use case where I need to call the method with object being a nullable Guid

Nullable<Guid> guid = Guid.NewGuid();
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("myGuid", guid);
MyFunc(parameters);

When I am trying to get object's type it appears to be System.Guid

parameters["myGuid"].GetType()

How can I know if the object is nullable? Am I losing nullable when sending an object as method argument?

CodePudding user response:

When you call parameters.Add("myGuid", guid) you're boxing the value of guid. When you box a Nullable<T>, the result is either a null reference or a boxed T... there's no trace of the nullability any more. In other words, there's no object representation of a Nullable<T>.

So no, you can't tell that the original type of the guid variable was Nullable<Guid>.

Note that you don't need a dictionary to demonstrate that. This shows the same thing:

Nullable<Guid> guid = Guid.NewGuid();
object boxed = guid;
Type type = boxed.GetType(); // System.Guid

CodePudding user response:

You have to check whether the dictionary item is same type Nullable<Guid> like below.

if( parameters["myGuid"] is Nullable<Guid>){

}

If you directly call GetType() and the value it was having null value in the dictionary then you would have null exception.

  •  Tags:  
  • Related