Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the type from a nullable variable

public class MyType
{
    public int? MyId { get; set; }    
}

MyType myType = new MyType();
myType.MyId.GetType()

the last line returns an exception since MyId is not set (ie. it's null). How I get the type (int? or even int) in this case? Note, int? is used as an example, the variable may have any type, this is just a simplified example.

Note, according to Microsoft, this is supposed to work:

int? a = 17;
Type typeOfA = a.GetType();
Console.WriteLine(typeOfA.FullName);
// Output:
// System.Int32

and it does work when the value is assigned...

EDIT.

Looking at some of the replies and comments, I would like to add that in code, I pass myType.MyId as an object to a method that needs to figure out its type. Basically it looks similar to:

public void RunQuery(string sql, List<(string parameterName, object parameterValue)> parameters)

so myType.MyId is passed into RunQuery as parameterValue

like image 452
user19754 Avatar asked Jul 24 '26 00:07

user19754


1 Answers

You can use reflection to get declared type of a property (which is known at compile time):

Type t = typeof(MyType).GetProperty(nameof(MyType.MyId)).PropertyType;

And GetType() is used to figure out the actual type of an object in runtime, but that does not make sense for a null reference.

Edit:

When you cast Nullable<T> to an Object, its value is boxed, so, if it was null, you will get just an Object variable with null reference, and you won't be able to find out the type any more.

So, you should somehow change your infrastructure to make the type be passed with your parameter. The fastest workaround is to pass it explicitly

List<(string parameterName, object parameterValue, Type parameterType)> parameters

Check out System.Data.SqlClient.SqlParameter, I am not sure, but this is probably exactly what you need to use.

like image 78
Bagdan Gilevich Avatar answered Jul 25 '26 13:07

Bagdan Gilevich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!