تبدیل یک مقدار رشته ای به یک Enum

با فرض اینکه یک TextBox و یک دکمه در روی فرم دارید و می خواهید که مقدار رشته وارد شده در TextBox را به یک مقدار Enum تبدیل کنید می توانید از کد زیر استفاده نمایید :

using System;
using System.Windows.Forms;

namespace CovertStringToEnum
{
    public partial class Form1 : Form
    {
        public enum Names
        {
            Siavash, Sara, Younes, Soroush
        }

        public static T ConvertStringToEnum(string name)
        {
            return (T)Enum.Parse(typeof(T), name);
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.textBox1.Text))
            {
                string userInput = this.textBox1.Text;
                Names userInputToNames = ConvertStringToEnum<Names>(userInput);

                if (userInputToNames == Names.Siavash)
                {
                    MessageBox.Show("The value you enter is siavash");
                }
            }
        }
    }
}