Mark Lalor
Mark Lalor

Reputation: 7907

C# make method required

I have a class with a method that when not called causes a crash.

Is there a way to make a compilation failure when the method isn't called?

Edit:

So what I have is basically a class that makes an istance of another class (a form) and it is a mesagebox with a do not show again option. Here's an example of how you'd use it.

public partial class Form1 : Form {
    DontShowAgainBox box;
    public void AlertYes() {
        if (box.form.showagain.Checked)
            t1.Text = "You chose yes (checked)!!!";
        else
            t1.Text = "You chose yes (unchecked)!!!";
    }
    public void AlertNo() {
        if (box.form.showagain.Checked)
            t1.Text = "You chose no (checked)!!!";
        else
            t1.Text = "You chose no (unchecked)!!!";
    }
    public Form1() {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e) {
        box = new DontShowAgainBox("Warning", "Are you sure?");

        Action yesaction = new Action(AlertYes);
        box.Bind_Yes(yesaction);

        Action noaction = new Action(AlertNo);
        box.Bind_No(noaction);

        box.SetNoButton("Nope");
        box.SetYesButton("I'm sure");

        box.Show();
    }
}

There's another method that you can hide the "No" button with also.

But the yes button is in every instance of the class so it needs to have a function associated with it or else... crash.

Upvotes: 1

Views: 366

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 134035

It is not possible for the compiler or linker to say, at build time, "Hey, this method that was supposed to be called wasn't called!" You can't make the compiler issue an error message because client code didn't call a particular method.

What you're asking is not possible.

Upvotes: 2

Scott C Wilson
Scott C Wilson

Reputation: 20026

Why not just test for this in software instead of crashing?

if (!init_called) { 
   print error
   exit
}

Upvotes: 5

Related Questions