Use Instance of a Class as parameter

Hello dear Community,

I’m a liiiittle bit new to AX and have a (probably) simple question for you.

I’m working with AX 2012.

Let’s assume I’ve got three classes.

“MyClass”, “MyFirstClass” and “MySecondClass”.

MyFirstClass has just one method:

public void howOldAmI(int _age)

{

info(strFmt(“You are %1 years old!”, _age));

}

MySecondClass has also just one method:

public void sayMyName(str _myName)

{

info("My Name is " + _myName);

}

The crucial class is “MyClass”.

It has two methods:

public void AgeOrName(str _ageOrName)

{

switch (_ageOrName)

{

case ‘age’ :

mfc = new MyFirstClass();

this.doSomething(/instance of the class/);

break;

case ‘name’ :

msc = new MySecondClass();

this.doSomething(/instance of the class/);

break;

}

}

public void doSomething(str _ageOrName)

{

_ageOrName.method()

}

I know str is the wrong type of parameter in this case. And this is my question.

How can I use an instance of a class as parameter?

Thanks in advance!

Just use the parameter as Class

public void doSomething(MySecondClass _secondClass)

{

_ageOrName.method()

}

look at \Classes\InventUpdate\movement

Good Morning Karanthi,

thanks for your reply.

But it’s not always the “MySecondClass”.

If the User says “age”, it has to be the “MyFirstClass”. So in this case, I could never use methods of “MyFirstClass”, it would be always “MySecondClass”.

I hope you understand what I mean.

Kind regards

There are many ways and the choice depend on your particular requirements, which we obviously don’t know.

For instance, you can let your classes to implement an interface with a single method (doSomething()) and declare the parameter with the type of the interface. The compiler will ensure that the method must be called with a class implementing the interface and the polymorphic call will run doSomething() method of the concrete class.

This is nothing specific to Dynamics AX - these are basics of object-oriented programming.

Hello Martin, thanks for your reply!

Gread idea to use an interface, and of course it works fine.

Kind regards