Is there a reason to do type comparisons this way?

I'm used to seeing old code like

if (true)
{
    ...
}

where it is intuitively clear that someone was lazy or too careful when making changes. Today I came across this snippet, and I'm curious if there is a functional difference between making such a comparison as follows:

private static bool logField(Type t, string fieldname)
{
    if (t.ToString() == typeof (Property).ToString())
    {
        ...
    }
    return true;
}

and do it like this:

private static bool logField(Type t, string fieldname)
{
    if (t == typeof (Property))
    {
        ...
    }
    return true;
}
+3
source share
5 answers

No, getting an object of type from 2 instances of the same type will always return a reference to an object of the same type in memory. This means that performing an equality check (==) is sufficient.

Essentially a call: if (t.ToString () == typeof (Property) .ToString ())

ToString() , t - .

0

, - . , , , . typeof(Property) , t , , , , .

, ... .

+6

.

, , t null.

+3

, , Property.

"", , - , t .

-

if (t is Property)
+1
source

I would say that the first approach was probably made by someone unfamiliar with C #, no need to be lazy. String comparisons will work in most cases, with the exception of:

  • If tnull, he would throw a null-reference exception.
  • It does not consider namespaces.

I would recommend the second case if you do not need the edge case # 2.

0
source

Source: https://habr.com/ru/post/1755861/


All Articles