# Get the enumerate type components from the string counterpart

**URL:** <https://discourse.julialang.org/t/get-the-enumerate-type-components-from-the-string-counterpart/23083>\
**Category:** General Usage\
**Tags:** enum\
**Created:** [April 12, 2019, 3:07pm UTC](https://discourse.julialang.org/t/get-the-enumerate-type-components-from-the-string-counterpart/23083 "2019-04-12T15:07:52Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![MatthijsCox](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/matthijscox/32/42831_2.png) [@MatthijsCox](https://discourse.julialang.org/u/MatthijsCox)\
**Post date:** [March 23, 2020, 3:14pm UTC](https://discourse.julialang.org/t/get-the-enumerate-type-components-from-the-string-counterpart/23083/11 "2020-03-23T15:14:07Z")

</div>

I also would like this kind of functionality for all my Enums, but I don’t like declaring constants for every enum.

I’ve arrived so far on the solution below. But I should probably write my own enum macro, similar to [this discussion on enum dot access](https://discourse.julialang.org/t/encapsulating-enum-access-via-dot-syntax/11785):

```julia
function get_instance(enum::DataType, str::String)
	idx = findfirst(x -> x==str, instance_names(enum))
	if idx == nothing
		throw(ArgumentError("invalid value for Enum $enum: $str"))
	else
		return enum(idx-1)
	end
end
instance_names(enum::DataType) = string.(instances(enum))

@enum Fruits begin
    apple
	pear
	banana
end
Fruits(str::String) = get_instance(Fruits, str)
Base.convert(::Type{Fruits}, str::String) = Fruits(str)

```

Now this works fine:

```julia
julia> Fruits("banana")
banana::Fruits = 2

julia> Fruits("monkey")
ERROR: ArgumentError: invalid value for Enum Fruits: monkey

```

I had to add the Base.convert since I am creating an enum instance from a constructor:

```julia
struct FruitBowl
   fruit::Fruits
end

julia> bowl = FruitBowl("banana")
julia> bowl.fruit
banana::Fruits = 2

```

I do not know why I could not dispatch on the Enum type though. typeof(Fruits) returned Datatype, not Enum.

---

_[View the full topic](https://discourse.julialang.org/t/get-the-enumerate-type-components-from-the-string-counterpart/23083)._
