How to Get the Lowercase Name of an Object, Even When Null, in C#

How to get the lowercase name of an object, even when null, in C#

Jeff is correct. That's like asking what kind of cake would have been in an empty box with no label.

As an alternative to Fortran's answer you could also do:

string TypeNameLower<T>(T obj) {
return typeof(T).Name.ToLower(CultureInfo.InvariantCulture);
}

string TypeNameLower(object obj) {
if (obj != null) { return obj.GetType().Name.ToLower(CultureInfo.InvariantCulture); }
else { return null; }
}

string s = null;
TypeNameLower(s); // goes to the generic version

That way, C# will pick the generic one at compile time if it knows enough about the type you're passing in.

.NET : How do you get the Type of a null object?

So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.

Not necessarily. The best that you can say is that it is an object. A null reference does not point to any storage location, so there is no metadata from which it can make that determination.

The best that you could do is change it to be more generic, as in:

public void GetParameterValue<T>(out T destination)
{
object paramVal = "Blah";
destination = default(T);
destination = Convert.ChangeType(paramVal, typeof(T));
}

The type of T can be inferred, so you shouldn't need to give a type parameter to the method explicitly.

Null check String.ToLower in Linq Where expression

Unfortunately I couldn't use C# 6.0 features at this point.

I ended up creating an extension method to filter the list, comparing with another extension method, Contains, that accepts a StringComparison parameter as suggested from @robert-mckee and demonstrated from @jeppe-stig-nielsen.

public static IList<Order> FilterOrders(this IList<Order> orders, string filterText)
{
var filtered = orders.Where(order =>
order.OrderIdFullOrderNumber.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.Name.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.Status.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.TimeRemaining.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.Address.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.City.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.State.Abbrev.Contains(filterText, StringComparison.OrdinalIgnoreCase) ||
order.PostalCode.Contains(filterText, StringComparison.OrdinalIgnoreCase)).ToList();
return filtered;
}

public static bool Contains(this string source, string value, StringComparison comparison)
{
if (string.IsNullOrWhiteSpace(source))
{
return false;
}

return source.IndexOf(value, comparison) >= 0;
}

How to safely .ToLower().Contains() on possible null property

Sometimes ProductName or ProductParentName are null so my application crashes.

Assuming this it to be executed server side and not in memory,

Keep it simple and check for null before apply functions.

return f => ((f.ProductName != null && f.ProductName.ToLower().Contains(searchString))
|| (f.ProductParentName != null && f.ProductParentName.ToLower().Contains(searchString)));

The framework should be able to translate this to SQL.

How to distinct between (object)null and (decimal?)null when passed in object parameter?

In your example it is impossible to determine whether it was an object or a decimal?. In both cases, simply a null reference is passed along, the type information is not. You can capture the type information using generics:

public static void Main()
{
object obj = null;
decimal? nullDecimal = null;

Test(obj); // prints Something else
Test(nullDecimal); // prints Nullable decimal
}

public static void Test<T>(T value)
{
if (typeof(T) == typeof(decimal))
{
Console.WriteLine("Decimal");
return;
}

if (typeof(T) == typeof(decimal?))
{
Console.WriteLine("Nullable decimal");
return;
}

Console.WriteLine("Something else");
}

With this, whether the value you pass is null or not, the compile-time type is automatically captured.

GetType on Nullable Boolean

You're calling GetType on a NULL Reference (The result of boxing a Nullable Type with No Value).

bool? b = new bool?(); is equivalent to bool? b = null;

Try this to get the correct result:

bool? b = new bool?(false);
Console.Write(b.GetType()); // System.Boolean

The documentation means that if you call GetType() successfully on a Nullable object that has value (Not Null). You get the Underlying type which is System.Boolean. But you can't call any method using a NULL reference and this is a general rule that applying to any reference type.

To clear the equivalence point between = null and new bool?(), check this Fiddle. Both generates the same IL:

IL_0001:  ldloca.s   V_0
IL_0003: initobj valuetype [mscorlib]System.Nullable`1<bool>

and

IL_0009:  ldloca.s   V_1
IL_000b: initobj valuetype [mscorlib]System.Nullable`1<bool>

How to test a null value variable if it's a string?

You cannot check the type of null because null has no type. It doesn't reference anything at all, therefore there is nothing that C# can look at to find out the actual type.

(Everyone else seems to be answering the question "How can I tell if a string reference is null or empty - but I think the question is "how can I tell if the underlying type of a null reference is string...)

There might be a way to fiddle it though - you might be able to use a generic method as mentioned here:

.NET : How do you get the Type of a null object?

(That link was posted by someone else - not me - as a comment to your original post!)

How does the debugger get type information about an object initialized to null?

It seems like you're confusing the type of the reference with the type of the value that it points to. The type of the reference is embedded into the DLL metadata and as readily accessible by the debugger. There is also aditional information stored in the associated PDB that the debugger leverages to provide a better experience. Hence even for null references a debugger can determine information like type and name.

As for NullReferenceException. Could it also tell you the type on which it was querying a field / method ... possibly. I'm not familiar with the internals of this part of the CLR but there doesn't seem to be an inherent reason why it couldn't do so.

But I'm not sure the added cost to the CLR would be worth the benefit. I share the frustration about the lack of information for a null ref exception. But more than the type involved I want names! I don't care that it was an IComparable, i wanted to know it was leftCustomer.

Names are somethnig the CLR doesn't always have access to as a good portion of them live in the PDB and not metadata. Hence it can't provide them with great reliability (or speed)

Type of the null value using F#

let getStaticType<'T>(_x : 'T) = typeof<'T>
let a : string = null
let b : int[] = null
let typ1 = getStaticType a
let typ2 = getStaticType b
printfn "%A %A" typ1 typ2
// System.String System.Int32[]


Related Topics



Leave a reply



Submit