Why does GetComponent() return boolean?

In c#, to check if some game object has a component, I can just type:

if (obj.GetComponent<SomeComponent>()) { //Checks if it has SomeComponent
     obj.GetComponent<SomeComponent>().doSomething(); 
}

Why is this possible? GetComponent is supposed to return the component, not true or false.
I have seen other people use this:

component = obj.GetComponent<SomeComponent>();
if (component != null) {
     component.doSomething();
}

What is the correct way of doing this?

Unity objects have an overloaded bool operator that allows you to use syntax like in your first example. However, the second example is better as it avoids calling GetComponent (a somewhat expensive function) 2x.

When you write:

if (obj.GetComponent<SomeComponent>()) { //Checks if it has SomeComponent
    obj.GetComponent<SomeComponent>().doSomething();
}

You should interpret that as:

if (obj.GetComponent<SomeComponent>() != null) { //Checks if it has SomeComponent
    obj.GetComponent<SomeComponent>().doSomething();
}

The method doesn’t return true or false, it returns an object (a pointer to a valid object) or null (a null pointer).

Note that:
if (null) {
// this code will never be executed
}
if (somethingThatIsNotNull) {
// this code will always be executed
}

That’s also similar to writing:
if (0) {
// this code will never be executed
}
if (someThatIsNotZero) {
// this code will always be executed
}

In this case, 0 is not a boolean “false”, but the if evaluates to false. And someThatIsNotZero is not boolean “true”, but the if evaluates to true.

Also, the second way could also be writen like this:

    component = obj.GetComponent<SomeComponent>();
    if (component) {
        component.doSomething();
    }

and it works.

There’s no correct one, but between the first and second method you posted the first one does some redundant work calling GetComponent twice. In any case, that has nothing to do with using “something != null” or “something” in the if condition, and there’s no correct way to do it, both are valid an equivalent so it’s a matter of taste.

Also, there’s one more valid syntax that’s kind of a mix of both:

    if (component = obj.GetComponent<SomeComponent>()) {
        component.doSomething();
    }

Note the single “=” instead of the common “==”. That if condition actually assignes the value returned by “obj.GetComponent()” to the “component” variable, and then evaluates the content of “component”. Some people like to do this things, and it’s also completelly valid.