Home > other >  how to use the variable as the name of an object?
how to use the variable as the name of an object?

Time:11-24

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!

CodePudding user response:

  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.
  •  Tags:  
  • c#
  • Related