| Products & Services | Industries | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
| On this page… |
|---|
.NET Properties in the MATLAB Workspace .NET Methods in the MATLAB Workspace |
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.
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.
| Reference | NetSample |
|---|---|
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 Name | Purpose |
|---|---|
| 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.
Copy the contents of the matlabroot\extern\examples\net\NetSample directory to a working directory, such as C:\work.
From your development tool, open NetSample as a project and build it as a DLL.
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.
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.
The following topics describe using .NET 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
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# Keyword | MATLAB Attribute |
|---|---|
| public, static | Access = public |
| protected, private, internal | Not visible to MATLAB |
| get, set | Access = public |
| Get | GetAccess = public, SetAccess = private |
| Set | SetAccess = public, GetAccess = private |
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# Keyword | MATLAB Mapping |
|---|---|
| public | Supported |
| protected, private, internal, protected internal | Not visible to MATLAB |
The SampleProperties class defines the following public properties:
stringProp
doubleProp
readOnlyProp
writeOnlyProp
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.stringPropMATLAB displays:
newVal = This is a static property
The SampleFields class defines the following fields:
publicField
protectedField
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, SuperclassesThe 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
You cannot pass a cell array to a property, or view protected properties in MATLAB.
The following topics describe using .NET methods in MATLAB.
Use the following MATLAB functions to view the methods of a class. You can use these functions without creating an instance of the class.
methods — View method names
methods with '-full' option — View method names with argument list
methodsview — Graphical representation of method list
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.
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).
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
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
MATLAB maps C# keywords to MATLAB method access attributes, as shown in the following table.
| C# Keyword | MATLAB Attribute |
|---|---|
| ref | RHS, LHS |
| out | LHS |
| params | Array of particular type |
| protected, private, internal, protected internal | Not visible to MATLAB |
| VB.NET Keyword | MATLAB Attribute |
|---|---|
| ByRef | LHS, RHS |
| ByVal | RHS |
| Optional | Mandatory |
MATLAB uses the following rules to populate method signatures.
obj is the output from the constructor.
this is the object argument.
RetVal is the return type of a method.
All other arguments use the .NET metadata.
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 operator | MATLAB methods |
|---|---|---|
| + (binary) | op_Addition | plus, + |
| - (binary) | op_Subtraction | minus, - |
| * (binary) | op_Multiply | mtimes, * |
| / | op_Division | mrdivide, / |
| && | op_LogicalAnd | and, & |
| || | op_LogicalOr | or, | |
| == | op_Equality | eq, == |
| > | op_GreaterThan | gt, > |
| < | op_LessThan | lt, < |
| != | op_Inequality | ne, ~= |
| >= | op_GreaterThanOrEqual | ge, >= |
| <= | op_LessThanOrEqual | le, <= |
| - (unary) | op_UnaryNegation | uminus, -a |
| + (unary) | op_UnaryPlus | uplus, +a |
The SampleMethods class defines the following methods:
addTwoDoubles
multiplyInts
refOutTest
paramsTest
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 =
5To call the nonstatic method multiplyInts, you must first create an object:
obj = netdoc.SampleMethods; db2 = obj.multiplyInts(2, 3)
MATLAB displays:
db2 =
6To 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 =
12To 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 =
21The SampleMethodSignature class defines the following three constructors:
netdoc.SampleMethodSignature obj SampleMethodSignature
netdoc.SampleMethodSignature obj SampleMethodSignature (double scalar d)
netdoc.SampleMethodSignature obj SampleMethodSignature (System.String s)
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.
You cannot pass a cell array to a .NET method or call any delegates. The methods and methodsview functions do not list generic methods.
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')
endCreate 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;
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);
![]() | Getting Started with .NET | Handling .NET Data in MATLAB Software | ![]() |

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 |