Products & Services Industries Academia Support User Community Company

Learn more about MATLAB   

Using a .NET Object

Creating a .NET Object

You often need to create objects when working with .NET classes. An object is an instance of a particular class. Methods are functions that operate exclusively on objects of a class. Data types package together objects and methods so that the methods operate on objects of their own type. For more information about objects, see Using Objects in the MATLAB Programming Fundamentals documentation.

You construct .NET objects in the MATLAB workspace by calling the class constructor, which has the same name as the class. The syntax to create a .NET object classObj is:

classObj = namespace.ClassName(varargin)

where varargin is the list of constructor arguments to create an instance of the class specified by ClassName in the given namespace. For an example, see Select a Constructor in Getting Started with .NET.

Using netdoc.NetSample

MATLAB includes a collection of sample C# classes in an assembly called NetSample. The examples in this topic use these classes to illustrate working with .NET objects in MATLAB.

ReferenceNetSample

Namespace

netdoc

Assembly

NetSample (in NetSample.dll)

Source files

NetSample.sln and .cs files

Source directory

matlabroot\extern\examples\net\NetSample

NetSample contains the following classes.

Class NamePurpose
SampleProperties

Sample declarations to show how MATLAB handles .NET properties

SampleFields

Sample declarations to show how MATLAB handles .NET fields

SampleMethods

Sample declarations to show how MATLAB handles .NET methods

SampleMethodSignature

Sample declarations to show how MATLAB displays .NET method signatures

To use the NetSample classes, build an application using a C# development tool, like Microsoft Visual Studio. The following are basic steps to do this; consult your development tool documentation for specific instructions.

  1. Copy the contents of the matlabroot\extern\examples\net\NetSample directory to a working directory, such as C:\work.

  2. From your development tool, open NetSample as a project and build it as a DLL.

  3. The name of this assembly is NetSample. Note the full path to the NetSample.dll file. Since it is a private assembly, you must use the full path to load it in MATLAB.

  4. After you load the assembly, if you modify and rebuild it, you must restart MATLAB to access the new assembly. You cannot unload an assembly in MATLAB.

.NET Properties in the MATLAB Workspace

The following topics describe using .NET properties in MATLAB.

Using Properties in MATLAB

Use the properties function to view property names. For an example using the System.DateTime structure, see View Properties. To get and set the value of a class property, use the standard MATLAB dot notation:

x = myObject.MyProp; %get
myObject.MyProp = y; %set

C# Property Access Modifiers

MATLAB maps C# keywords to MATLAB property attributes, as shown in the following table. For more information about MATLAB properties, see Property Attributes in the MATLAB Object-Oriented Programming documentation.

C# KeywordMATLAB Attribute
public, staticAccess = public
protected, private, internalNot visible to MATLAB
get, setAccess = public
GetGetAccess = public, SetAccess = private
SetSetAccess = public, GetAccess = private

.NET Fields in the MATLAB Workspace

MATLAB represents public fields as properties. For example, the System.String class has one field, Empty. To view it, type:

str = System.String('my new string');
properties(str)

MATLAB displays:

Properties for class System.String:
    Length
    Empty

MATLAB maps C# keywords to MATLAB field attributes, as shown in the following table.

C# KeywordMATLAB Mapping
publicSupported
protected, private, internal, protected internalNot visible to MATLAB

Using .NET Properties Example

The SampleProperties class defines the following public properties:

SampleProperties Class.  

using System;
namespace netdoc
{
    class SampleProperties
    {
        // string property
        private static string stringField = "The MathWorks";
        public static string stringProp
        {
            get { return stringField; }
            set { stringField = value; }
        }

        // read/write property
        private double doubleField = 8.9;
        public double doubleProp
        {
            get { return doubleField; }
            set { doubleField = value; }
        }

        // read-only property
        private double readField = 0;
        public double readOnlyProp
        {
            get { return readField; }
        }

        // write-only property
        private double writeField = 0;
        public double writeOnlyProp
        {
            set { writeField = value; }
        }
    }
}

Create Object.   Load the assembly and create object obj:

sampleInfo = NET.addAssembly('c:\work\NetSample.dll');
obj = netdoc.SampleProperties

MATLAB displays the object as follows:

obj = 
  netdoc.SampleProperties handle
  Package: netdoc

  Properties:
      stringProp: [1x1 System.String]
      doubleProp: 8.9000
    readOnlyProp: 0

  Methods, Events, Superclasses

MATLAB displays the stringProp, doubleProp, and readOnlyProp properties, but not the writeOnlyProp property. MATLAB also does not display properties defined with the private keyword, such as stringField and doubleField.

View Property Values.   To view the value of stringProp, type:

obj.stringProp

MATLAB displays:

ans = 
The MathWorks

Use Property Values.   To use the properties, type:

db1 = obj.doubleProp
db2 = obj.readOnlyProp

MATLAB displays:

db1 =
    8.9000
db2 =
     0

Modify Property Values.   To modify the properties, type:

obj.doubleProp = 5;
obj.writeOnlyProp = 6;
obj

MATLAB displays (in part):

obj = 

  Properties:
      stringProp: [1x1 System.String]
      doubleProp: 5
    readOnlyProp: 0

To modify the static property stringProp, type:

NET.setStaticProperty('netdoc.SampleProperties.stringProp', ...
    'This is a static property');
newVal = obj.stringProp

MATLAB displays:

newVal = 
This is a static property

Using .NET Fields Example

The SampleFields class defines the following fields:

SampleFields Class.  

using System;
namespace netdoc
{
    class SampleFields
    {
        public Int32 publicField;
        protected string protectedField;
    }
}

Create Object.   Load the assembly and create object obj:

NET.addAssembly('c:\work\NetSample.dll')
obj = netdoc.SampleFields;

Modify Field Values.   To set the value of the field publicField, type:

myValue = 3;
obj.publicField = myValue

MATLAB displays:

obj = 
  netdoc.SampleFields handle
  Package: netdoc

  Properties:
    publicField: 3

  Methods, Events, Superclasses

The publicField property is of type Int32. When you set the value to myValue, which is of MATLAB type double, MATLAB automatically converts the value to the proper type, as described in Passing Data to a .NET Object. Type:

class(myValue)
class(obj.publicField)

MATLAB displays:

ans =
double
ans =
int32

Limitations to Support of .NET Properties

You cannot pass a cell array to a property, or view protected properties in MATLAB.

.NET Methods in the MATLAB Workspace

The following topics describe using .NET methods in MATLAB.

Getting Method Information

Use the following MATLAB functions to view the methods of a class. You can use these functions without creating an instance of the class.

You could find the methodsview window easier to use as a reference guide because you do not need to scroll through the Command Window to find information. For example, open a methodsview window for the System.String class:

methodsview('System.String')

The following topics refer to method signatures in this display.

Calling Nonstatic Methods

You can use either function notation or dot notation syntax for calling standard (nonstatic) methods of a class. These functions operate on an object. For example, Contains is a method of the System.String class. Its method signature is:

logical scalar RetVal Contains(System.String this, 
  System.String value)

To use this method, first create an object, str1:

str1 = System.String('The colors are red and white');

To call Contains using function notation, type:

flag = Contains(str1,'red');

To call Contains using dot notation, type:

flag = str1.Contains('red');

In either case, the value of flag is 1 (true).

Calling Static Methods

A static method does not operate on a single object. You must use the fully qualified name when you call a static method. For example, Concat is a static method of the System.String class. One of its method signatures is:

Static System.String RetVal Concat(System.String str0, 
  System.String str1, System.String str2)

Given the following value for object str2:

str2 = System.String(' and blue');

you must use the function notation to concatenate str1 and str2:

newstr = System.String.Concat(str1,str2)

MATLAB displays:

newstr = 
The colors are red and white and blue

Calling .NET Properties That Take an Argument

MATLAB represents a property that takes an argument as a method. For example, the System.String class has two properties, Chars and Length. The Chars property gets the character at a specified character position in the System.String object. :

str = System.String('my new string');
methods(str)

MATLAB displays (in part):

Methods for class System.String:

Chars             Insert            ToCharArray       findobj 
Clone             IsNormalized      ToLower           findprop
CompareTo         LastIndexOf       ToLowerInvariant  ge      
Contains          LastIndexOfAny    ToString          gt      
...

To see the first character, type:

str.Chars(0)

MATLAB displays:

ans =
m

C# Method Access Modifiers

MATLAB maps C# keywords to MATLAB method access attributes, as shown in the following table.

C# KeywordMATLAB Attribute
refRHS, LHS
outLHS
paramsArray of particular type
protected, private, internal, protected internalNot visible to MATLAB

VB.NET KeywordMATLAB Attribute
ByRefLHS, RHS
ByValRHS
OptionalMandatory

MATLAB uses the following rules to populate method signatures.

Operator Overloading

MATLAB supports overloaded operators, such as the C# operator symbols + and *, as shown in the following table. MATLAB implements all other overloaded operators, such as % and +=, by their static method names, op_Modulus and op_AdditionAssignment. For a complete list of operator symbols and the corresponding operator names, see http://msdn.microsoft.com/en-us/library/2sk3x8a7(VS.71).aspx on the Microsoft Developer Network Web site.

C++ operator symbol.NET operatorMATLAB methods
+ (binary) op_Additionplus, +
- (binary) op_Subtractionminus, -
* (binary) op_Multiplymtimes, *
/op_Divisionmrdivide, /
&&op_LogicalAndand, &
||op_LogicalOror, |
==op_Equalityeq, ==
>op_GreaterThangt, >
<op_LessThanlt, <
!=op_Inequalityne, ~=
>=op_GreaterThanOrEqualge, >=
<=op_LessThanOrEqualle, <=
- (unary)op_UnaryNegationuminus, -a
+ (unary)op_UnaryPlusuplus, +a

Using .NET Methods Example

The SampleMethods class defines the following methods:

SampleMethods Class.  

using System;
namespace netdoc
{
    class SampleMethods
    {
        //static method
        public static double addTwoDoubles(double num1, double num2)
        {
            return num1 + num2;
        }
        
        //standard method
        public Int32 multiplyInts(Int32 num1, Int32 num2)
        {
            return num1 * num2;
        }

        //test ref and out keyword
        public void refOutTest(ref double db1, out double db2)
        {
            db1 = db1 * 2;
            db2 = db1;
        }

        //test params keyword
        public int paramsTest(params int[] num)
        {
            int total = 0;
            foreach (int i in num)
            {
                total = total + i;
            }
            return total;
        }

    }
}

Calling Methods Examples.   If you have not already loaded the NetSample assembly, type:

NET.addAssembly('c:\work\NetSample.dll')

Call the static method addTwoDoubles:

db1 = netdoc.SampleMethods.addTwoDoubles(2, 3)

MATLAB displays:

db1 =
     5

To call the nonstatic method multiplyInts, you must first create an object:

obj = netdoc.SampleMethods;
db2 = obj.multiplyInts(2, 3)

MATLAB displays:

db2 =
           6

To capture the output from a method using the ref and out keywords, use the refOutTest method. Its function signature is:

[double scalar db1, double scalar db2] refOutTest
  (netdoc.SampleMethods this, double scalar db1)

Type:

[db4 db3] = obj.refOutTest(6)

MATLAB displays:

db4 =
    12
db3 =
    12

To call a method using a params keyword, use the paramsTest method. The function signature is:

	int32 scalar RetVal paramsTest(netdoc.SampleMethods this, 
  System.Int32[] num)

Type:

mat  = [1, 2, 3, 4, 5, 6];
mat = NET.convertArray(int32(mat));
db5 = obj.paramsTest(mat)

MATLAB displays:

db5 =
          21

Method Signature Example

The SampleMethodSignature class defines the following three constructors:

SampleMethodSignature Class.  

using System;
namespace netdoc
{
    public class SampleMethodSignature
    {
        public SampleMethodSignature ()
        {}
        
        public SampleMethodSignature (double d)
        { myDoubleField = d; }
        
        public SampleMethodSignature (string s)
        { myStringField = s; }

        public int myMethod(string strIn, ref double dbRef, 
					out double dbOut)
        {
            dbRef += dbRef;
            dbOut = 65;
            return 42;
        }

        private Double myDoubleField = 5.5;
        private String myStringField = "hello";
    }
}

Display Function Signature Example.   If you have not already loaded the NetSample assembly, type:

NET.addAssembly('c:\work\NetSample.dll')

Create an SampleMethodSignature object obj:

obj = netdoc.SampleMethodSignature;

To see the method signatures, type:

methods(obj, '-full')

Look for the following signatures in the MATLAB output:

netdoc.SampleMethodSignature obj SampleMethodSignature
netdoc.SampleMethodSignature obj SampleMethodSignature(double scalar d)
netdoc.SampleMethodSignature obj SampleMethodSignature(System.String s)

For more information about argument types, see Handling Data Returned from a .NET Object.

Limitations to Support of .NET Methods

You cannot pass a cell array to a .NET method or call any delegates. The methods and methodsview functions do not list generic methods.

.NET Events in the MATLAB Workspace

Use the addlistener function to handle events from .NET objects.

For example, you can monitor changes to files using the System.IO.FileSystemWatcher class in the System assembly. Create the following event handler M-file, eventhandlerChanged.m:

function eventhandlerChanged(source,arg)
disp('M-file changed')
end

Create a FileSystemWatcher object fileObj and watch the Changed event for M-files in the directory C:\work\temp.

fileObj = System.IO.FileSystemWatcher('c:\work\temp');
fileObj.Filter = '*.m';
fileObj.EnableRaisingEvents = true;
addlistener(fileObj, 'Changed', @eventhandlerChanged);

If you modify and save a file in the C:\work\temp directory, MATLAB displays:

M-file changed

The FileSystemWatcher documentation says that a simple file operation can raise multiple events.

To turn off the event handler, type:

fileObj.EnableRaisingEvents = false;

What Classes Are in a .NET Assembly?

The product documentation for your assembly contains information about its classes. However, you can use the NET.addAssembly command to read basic information about an assembly. For example, for the private assembly netdoc.NetSample, type:

sampleInfo = NET.addAssembly('c:\work\NetSample.dll');

Assembly netdoc.NetSample has five classes. To view the names, type:

sampleInfo.Classes

MATLAB displays:

ans = 
    'netdoc.SampleMethodSignature'
    'netdoc.SampleMethods'
    'netdoc.NetSample'
    'netdoc.SampleFields'
    'netdoc.SampleProperties'

For a description of the Sample* classes, see Using netdoc.NetSample. The NetSample class is empty; it is used to create the assembly name.

If your assembly has hundreds of entries, you can consult the product documentation, or open a window to an online document, such as the System namespace reference page on the Microsoft Developer Network. For information about using this documentation, see To Learn More About the .NET Framework. For example, to find the number of classes nclasses in mscorlib, type:

asm = NET.addAssembly('mscorlib');
[nclasses,x] = size(asm.Classes);
  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS