Pass parameters to .NET Constructor

Consider a .NET Assembly Assembly with a class Person with some set of properties like Age, FirstName, LastName, Address, and a constructor P = new Person().
In C# it is possible to predefine some fields right on contruction stage by using curly braces
C#:
var x = new Assembly.Person {FirstName="Homer",LastName="Simpson",Age=47};
Equal code would look in MATLAB like
MATLAB:
x = Assembly.Person();
x.FirstName = "Homer";
x.LastName = "Simpson";
x.Age = 47;
--> Is there a better, more compact way to construct such object in Matlab?

Answers (1)

Sameer
Sameer on 8 Nov 2024
Edited: Sameer on 8 Nov 2024
In MATLAB, when working with ".NET" objects, you typically don't have the same syntax flexibility as in "C#" for initializing objects with property values directly in the constructor. However, you can create a helper function or use a struct to streamline the initialization process.
Here's an example of how you might achieve a more compact syntax:
Using a Helper Function
You can define a helper function to initialize the properties of the "Person" object:
function person = createPerson(firstName, lastName, age)
person = Assembly.Person();
person.FirstName = firstName;
person.LastName = lastName;
person.Age = age;
end
Then, you can create a "Person" object like this:
x = createPerson("Homer", "Simpson", 47);
Using a Struct for Initialization
Alternatively, you can define a struct to hold the properties and then assign them in a loop:
props = struct('FirstName', "Homer", 'LastName', "Simpson", 'Age', 47);
x = Assembly.Person();
fields = fieldnames(props);
for i = 1:numel(fields)
x.(fields{i}) = props.(fields{i});
end
This approach allows you to define all properties in a single struct and then apply them to the object.
Hope this helps!

Products

Release

R2021a

Asked:

on 22 Jun 2021

Edited:

on 8 Nov 2024

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!