Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

Getting Started with .NET

What Is an Assembly?

Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources built to work together and form a logical unit of functionality.

To work with a .NET application, you need to make its assemblies visible to MATLAB. How you do this depends on how the assembly is deployed, either privately or globally.

To load a global assembly into MATLAB, use the short name of the assembly, which is the file name without the extension. To load a private assembly, you need the full path (directory and file name with extension) of the assembly. This information is in the product documentation for the assembly. Refer to the product documentation for everything you need to know to use your product.

MATLAB loads the following assemblies from the .NET Framework class library at startup:

To use any other .NET assembly, load the assembly using the NET.addAssembly command. After loading the assembly, you can work with the classes defined by the assembly.

For an example showing you how to find the information you need to work with assemblies, see:

For detailed information, see:

.NET Terminology

A namespace is a way to group identifiers. A namespace can contain other namespaces. In MATLAB, a namespace is a package. In MATLAB, a .NET type is a class.

The syntax namespace.ClassName is known as a fully qualified name.

.NET Framework System Namespace

The System namespace is the root namespace for fundamental types in the .NET Framework. This namespace also contains classes (for example, System.String and System.Array) and second-level namespaces (for example, System.Collections.Generic). The mscorlib and system assemblies, which MATLAB loads at startup, contain many, but not all System namespaces. For example, to use classes in the System.Xml namespace, load the system.xml assembly using the NET.addAssembly command. Refer to the Microsoft .NET Framework Class Library Reference to learn what assembly to use for a specific namespace.

Reference Type Versus Value Type

Objects created from .NET classes (for example, the System.Reflection.Assembly class) appear in MATLAB as reference types, or handle objects. Objects created from .NET structures (for example, the System.DateTime structure) appear as value types. You use the same MATLAB syntax to create and access members of classes and structures.

However, handle objects are different from value objects. When you copy a handle object, only the handle is copied and both the old and new handles refer to the same data. When you copy a value object, the object's data is also copied and the new object is independent of changes to the original object. For more information about these differences, see Copying Objects in the MATLAB Programming Fundamentals documentation.

Do not confuse an object created from a .NET structure with a MATLAB structure array (see Structures in the MATLAB Programming Fundamentals documentation). You cannot pass a structure array to a .NET method.

Example — Using System Resources

Suppose you want to work with calendar information and need to create variables to hold day, month, and year values. You can search the online Microsoft .NET Framework System namespace product documentation for data types and functions to support date and time functionality. For information about using this documentation, see To Learn More About the .NET Framework.

Get Assembly Information

The DateTime structure in the System namespace represents an instance of time, typically expressed as a date and time of day. Refer to the DateTime reference page for the following information:

View Properties

To see the available properties, type:

properties System.DateTime

MATLAB displays:

Properties for class System.DateTime:

    Date
    Day
    DayOfWeek
    DayOfYear
    Hour
    Kind
    Millisecond
    Minute
    Month
    Now
    UtcNow
    Second
    Ticks
    TimeOfDay
    Today
    Year
    MinValue
    MaxValue

View Methods

To use the Day, Month and Year properties, create a System.DateTime object. To find the function to use to create the object, type:

methods System.DateTime

MATLAB displays:

Methods for class System.DateTime:

Add                    GetType                ToUniversalTime        
AddDays                GetTypeCode            addlistener            
AddHours               IsDaylightSavingTime   delete                 
AddMilliseconds        Subtract               eq                     
AddMinutes             ToBinary               findobj                
AddMonths              ToFileTime             findprop               
AddSeconds             ToFileTimeUtc          ge                     
AddTicks               ToLocalTime            gt                     
AddYears               ToLongDateString       isvalid                
CompareTo              ToLongTimeString       le                     
DateTime               ToOADate               lt                     
Equals                 ToShortDateString      ne                     
GetDateTimeFormats     ToShortTimeString      notify                 
GetHashCode            ToString               

Static methods:

Compare                Parse                  op_GreaterThan         
DaysInMonth            ParseExact             op_GreaterThanOrEqual  
FromBinary             SpecifyKind            op_Inequality          
FromFileTime           TryParse               op_LessThan            
FromFileTimeUtc        TryParseExact          op_LessThanOrEqual     
FromOADate             op_Addition            op_Subtraction         
IsLeapYear             op_Equality 

Select a Constructor

The method to use to create an object is DateTime. This is known as the DateTime constructor. To call this method, you need to know its argument list, or function signature. Type:

methodsview System.DateTime

Search the list that MATLAB displays for entries beginning with:

System.DateTime obj DateTime(int32 scalar year, 

From the product documentation, you see that the following signature initializes a new instance of the DateTime structure to the specified year, month, and day.

Static int32 scalar RetVal DaysInMonth(int32 scalar year, 
  int32 scalar month)

Create an Object

Create an object dateObj for the date January 31, 2000:

dateObj = System.DateTime(2000,1,31);

This command sets the following properties:

dateObj.Day
dateObj.Month
dateObj.Year

to the values:

ans =
          31
ans =
          1
ans =
        2000

Display Object in the Command Window

To see how MATLAB displays object information, type:

dateObj

MATLAB displays:

dateObj = 

  System.DateTime
  Package: System

  Properties:
           Date: [1x1 System.DateTime]
            Day: 31
      DayOfWeek: [1x1 System.DayOfWeek]
      DayOfYear: 31
           Hour: 0
           Kind: [1x1 System.DateTimeKind]
    Millisecond: 0
         Minute: 0
          Month: 1
            Now: [1x1 System.DateTime]
         UtcNow: [1x1 System.DateTime]
         Second: 0
          Ticks: 630848736000000000
      TimeOfDay: [1x1 System.TimeSpan]
          Today: [1x1 System.DateTime]
           Year: 2000
       MinValue: [1x1 System.DateTime]
       MaxValue: [1x1 System.DateTime]

  Methods, Events, Superclasses

Work with Properties and Methods

Refer to the properties listed in View Properties. To see the day of the week, type:

dateObj.DayOfWeek

MATLAB displays:

ans =
    Monday

To get more information about dateObj, refer to the methods listed in View Methods. For example, to use the DaysInMonth method, look at its function signature in the methodsview window:

Static	int32 scalar RetVal	DaysInMonth	(int32 scalar year, 
  int32 scalar month)

This is a static method, and its inputs are year and month. To display the number of days in the dateObj month, type:

System.DateTime.DaysInMonth(dateObj.Year, dateObj.Month)

To determine if one date occurs before another date, look at the CompareTo function signature:

int32 scalar RetVal CompareTo(System.DateTime this, 
  System.DateTime value)

This method requires two DateTime objects, this and value. Create a second date, myDate, and compare it to dateObj:

myDate = System.DateTime(dateObj.Year,3,1);
dateObj.CompareTo(myDate)

MATLAB displays a signed number. According to the CompareTo documentation, if the number is less than zero, dateObj is "less than," or earlier than, myDate.

To calculate the number of days between these dates, use the DayOfYear property.

dateObj.DayOfYear - myDate.DayOfYear

Other methods to try:

dateObj.ToString
dateObj.IsDaylightSavingTime

Using Today and Now

Create an object, todayDate, with today's date:

todayDate = System.DateTime.Today;

The Today property only sets the date, so when you type:

todayDate.Hour

MATLAB displays:

ans =
           0

To display time information, type:

todayDate.Now

MATLAB displays values for the Hour, Minute, and Second properties.

Simplifying .NET Class Names

In a MATLAB command, you can refer to any class by its fully qualified name, which includes its package name. A fully qualified name can be rather long, making commands and functions, such as constructors, cumbersome to edit and to read. You can refer to classes by the class name alone (without a package name) if you first import the fully qualified name into MATLAB. The import function adds all classes that you import to a list called the import list. You can see what classes are on that list by typing import, without any arguments.

For example, to eliminate the need to type System. before every command in the previous example, type:

import System.*
import System.DateTime.*

To create the object, type:

dateObj = DateTime.Today;

To use a static method, type:

DaysInMonth(dateObj.Year, dateObj.Month);

Loading .NET Assemblies into MATLAB

If MATLAB does not automatically load your assembly, use the NET.addAssembly function. The syntax is:

asmInfo = NET.addAssembly('assemblyName');

You need to know if the assembly is global or private, as explained in What Is an Assembly?. Your product documentation has this information.

You cannot unload an assembly from MATLAB.

Handling Exceptions

MATLAB catches exceptions thrown by .NET and converts them into a NET.NetException object, which is derived from the MException class. The default display of NetException contains the Message, Source and HelpLink fields of the System.Exception class that caused the exception. For example:

try
  NET.addAssembly('C:\Work\invalidfile.dll')
catch e
  e.message
  if(isa(e, 'NET.NetException'))
    e.ExceptionObject
  end
end
  


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