how do i check if an object has a parent

hello everyone, i want to be able to check if this object has a parent, if so i want it to do send some messages to that parent, but that object could also have no parent, in which case i want it to do carry out other functions. but not sending messages to its parent. The
first thing i came up with was the following

if (transform.parent.parent != null){
    transform.parent.sendMessage("bla bla");
} 

that for some reason is giving me a null reference exeption on the first line of the if statement. i have no idea what to try next. any help is much apreciated. thank you all in advanced

If you are checking for both the parent and parent’s parent

if (transform.parent != null && transform.parent.parent != null){
    transform.parent.sendMessage("bla bla");
}

Also, the order of this check matters.

If you have 1 object whit 1 parent and chef for the parent 2, no problem, but if check for parent 3 you recive error because 2 no exist, then you can do:

if (transform.parent)
        {
            Debug.Log("you have 1 parent");
            if (transform.parent.parent)
            {
                Debug.Log("you have 2 parents");
                if (transform.parent.parent.parent)
                {
                    Debug.Log("you have 3 parents");
                    if (transform.parent.parent.parent.parent)
                    {
                        Debug.Log("you have 4 parents");
                        if (transform.parent.parent.parent.parent.parent)
                        {
                            Debug.Log("you have 5 parents");
                            if (transform.parent.parent.parent.parent.parent.parent)
                            {
                                Debug.Log("you have 6 parents, ask to mama");
                                // etc...
                            }
                        }
                    }
                }
            }
        }

For a recursive algorithm:

Transform parent = transform.parent;
int i = 1;
while (parent != null)
{
	Debug.Log("Reached parent " + i + ": " + parent.name);
    parent.SendMessage("example");

	parent = parent.parent;
	++i;
}
Debug.Log("No more parents");

looks like we got a code Egyptian.

Check if A is a parent of B

bool ParentCheck(Transform childTransform, Transform parentTransform){
    if(childTransform.parent!=null){
        if(childTransform.parent.transform==parentTransform){
            return true;
        }else{
            return ParentCheck(childTransform.parent,parentTransform);
        }
    }else{
        return false;
    }
}

Also childTransform.IsChildOf(parentTrasform) will give

true if this transform is a child,
deep child (child of a child) or
identical to this transform, otherwise
false.