I’m trying to create a class with a constructor:
class MyClass
{
public int VAR1;
public int VAR2;
public MyClass(int var1, int var2)
{
this.VAR1=var1;
this.VAR2=var2;
}
public int DoMath()
{
return this.VAR1+this.VAR2;
}
}
Ok, that example will probably work and once constructed the DoMath method will become available in the class instance.
What I would like to do is run some equations in the constructor, and depending on the outcome the DoMath method may or may not become available. So something like this:
class MyClass
{
public int VAR1;
public int VAR2;
public MyClass(int var1, int var2)
{
if(var1==var2) /*HERE IT CHECKS IF THE VARS ARE THE SAME*/
{ /*IF THEY'RE NOT THE SAME THEN THE DoMath METHOD IS UNAVAILABLE*/
this.VAR1=var1;
this.VAR2=var2;
}
}
public int DoMath()
{
return this.VAR1+this.VAR2;
}
}
Obviously this is only an example, but another way to explain would be this:
I need a class called “Process” where the constructor takes a process id as an argument, the constructor will need to check that this process actually exists before giving access to all the methods in the class.
Any one know how this is possible?
This is not possible as you want it. What you can do is provide a property
and set
this.canDoMathin the constructor as to whether or not you can do math. Then you should haveDoMaththrow anInvalidOperationExceptionifthis.canDoMathis false but the method is invoked.