Just expanding upon @Josh Einstein's answer.
Below are two extension methods to get the type of a variable even if it is currently set to null.
///
/// Gets an object's type even if it is null.
///
/// The type of the object.
/// The object being extended.
/// The objects type.
public static Type GetTheType(this T that)
{
return typeof(T);
}
///
/// Gets an object's type even if it is null.
///
/// The object being extended.
/// The objects type.
public static Type GetTheType(this object that)
{
if (that != null)
{
return that.GetType();
}
return null;
}
Also, here are two simple unit tests to test the extension methods.
///
/// Tests to make sure that the correct type is return.
///
[Test(Description = "Tests to make sure that the correct type is return.")]
public void Test_GetTheType()
{
var value = string.Empty;
var theType = value.GetTheType();
Assert.That(theType, Is.SameAs(typeof(string)));
}
///
/// Tests to make sure that the correct type is returned even if the value is null.
///
[Test(Description = "Tests to make sure that the correct type is returned even if the value is null.")]
public void Test_GetTheType_ReturnsTypeEvenIfValueIsNull()
{
string value = null;
var theType = value.GetTheType();
Assert.That(theType, Is.SameAs(typeof(string)));
}
Edit
Sorry, I forgot to mention that I was needing this exact same feature for a project I'm currently on. All credit still should go to @Josh Einstein :D