Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to use the variable as the name of an object?

it might be very simple or been asked before, so forgive me for asking it again. im trying to learn 🙂

if I had a string type variable in C# which would take any of the following values:
"Admin"
"Editor"
"Viewer"
and i also had 3 userforms with the same names as above, is there any way to simply use the variables value to call out a userform instead of going through a switch or if/else statement?
like, can you have something like:
userform(x).show?
x being the variable

would appreciate it alot!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. For "types", you should use Enums.
public enum UserType
{
    Admin,
    Editor,
    Viewer,
}
  1. If you have types that need string representations, you can let C# do it automatically for you, or write your own:
UserType userType = UserType.Admin;
string s = userType.ToString(); // "Admin"
string s2 = UserType.Admin.ToString(); // "Admin" as well

public static string GetType(UserType type) => type switch 
{
   UserType.Admin => "Boss",
   UserType.Editor => "Fact Checker",
   UserType.Viewer => "Reader Bee",
   _ => "",
};

For getting a form of that type, a Dictionary<UserType, Form> would be good:

Dictionary<UserType, Form> myForms = new(); // C#9 shorthand - "target typed new expression"
myForms.Add(UserType.Editor, editorForm);
myForms.Add(UserType.Admin, adminForm);
myForms.Add(UserType.Viewer, viewerForm);

editorForm.Text = UserType.Editor.ToString(); // use the built in string or...
editorForm.Text = GetType(UserType.Editor); // ... as defined above

If you want to show a specific form, then you can do:

UserType typeOfFormToShow = // ... 
myForms[typeOfFormToShow].Show(); // Ensure this form exists in your dictionary, though.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading