Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to know if method argument is a nullable type

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

parameters["myGuid"].GetType()

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading