# How to dispatch based on whether a type has fields or not?

**URL:** https://discourse.julialang.org/t/how-to-dispatch-based-on-whether-a-type-has-fields-or-not/28773
**Category:** New to Julia
**Created:** [September 15, 2019, 12:05am UTC](https://discourse.julialang.org/t/how-to-dispatch-based-on-whether-a-type-has-fields-or-not/28773 "2019-09-15T00:05:20Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![xiaodai](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/xiaodai/32/15937_2.png) [@xiaodai](https://discourse.julialang.org/u/xiaodai)
#### Post date: [September 15, 2019, 12:05am UTC](https://discourse.julialang.org/t/how-to-dispatch-based-on-whether-a-type-has-fields-or-not/28773/1 "2019-09-15T00:05:20Z")

</div>

I want to dispatch based on whether the type has fields or not. I have now

```julia
hasfieldnames(::Type{T}) where T = fieldnames(T) >= 1

fn(::Type{T}) where T = begin
   if hasfieldnames(T)
      _fn_has_field_name(T)
   else
      _fn_has_no_field_name(T)
   end
end

```

Is this the best way? I think the `if-else` is redundant and potentially bad for performance and can be gotten rid of if I knew how to make `fn` dispatch on whether `T` has field names or not.

---

<div class="post-metadata">

### Author: ![tkoolen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tkoolen/32/1603_2.png) [@tkoolen](https://discourse.julialang.org/u/tkoolen)
#### Post date: [September 15, 2019, 12:19am UTC](https://discourse.julialang.org/t/how-to-dispatch-based-on-whether-a-type-has-fields-or-not/28773/2 "2019-09-15T00:19:13Z")

</div>

You probably meant `fieldcount` instead of `fieldnames`. You could also use

```julia
hasfieldnames(::Type{T}) where T = isconcretetype(T) && !isprimitivetype(T) && sizeof(T) > 0

```

which I believe is equivalent, but has the advantage that it constant-folds, so that the compiler will completely remove the unused branch in the `if`-`else`.
