QueenSaphos
QueenSaphos

Reputation: 95

Writing Method in C# Which Creates Instance Of Class Using Parameter

A basic question: I am writing a C# app which has a menu, each menu item is going to open a new window. The windows will all be instances of the Window class.

instead of writing: (EditSettings being the desired name of the target window)

Window EditSettings = new Window();
EditSettings.Show();

for each one, could I not write a method something like the below, to create the instance?

private void OpenSelectedWindow(Window n)
{
    n = new Window();
    n.Show();
}

I can't call the method though - I tried:

OpenSelectedWindow(EditSettings);

Which doesn't work ("The name EditSettings does not exist in the current context'), OR

OpenSelectedWindow(Window EditSettings);

which doesn't work either

I am so rusty with C# and feel like a twit for asking this, but I can't seem to find examples of this on the internet. Can you create an instance of a class using a method?? What am I missing? Thank you.

Edit

The code all happens in the main Namespace:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    // Attempting to write a method that instances the class
    private void OpenSelectedWindow(Window n)
    {
        n = new Window();
        n.Show();

    }

    private void MenuItem_Click(object sender, RoutedEventArgs e)
    {
        //Calling the method
        OpenSelectedWindow(EditSettings);
    }
}

I have two .xaml files - EditSettings.xaml (empty) and MainWindow.xaml.

Upvotes: 0

Views: 718

Answers (1)

helb
helb

Reputation: 7783

You can use generics for this one:

private T OpenSelectedWindow<T>() where T : Window, new()
{
    T n = new T();
    n.Show();
    return n;
}

Use the method like this:

EditSettings editSettingsWindow = OpenSelectedWindow<EditSettings>();

Upvotes: 1

Related Questions