Modeling C# extension methods

This content applies to version 7.5.2 or later. You can model C# 3.0 extension methods to generate code. Extension methods in the code can also be generated in the model using a C#-to-UML transformation.

Before you begin

To use the stereotypes required in this procedure, you must apply the C# transformation profile to the model.

About this task

To create extension methods in the model:

Procedure

  1. Select or create a static C# class.
    1. In the Project Explorer view or diagram editor, right-click a model element that can contain a class; then click Add UML > Class.
    2. Click the Stereotype tab.
    3. Click Apply Stereotypes, select CSharp Class, and then click OK.
    4. Under Stereotype Properties, set static to True.
  2. Add a static UML operation with the «CSharp Extension Method» stereotype to the class.
    1. Right-click the class and click Add UML > Operation.
    2. In the Properties view, click the General tab; then select Static.
    3. Click the Stereotype tab.
    4. Click Apply Stereotypes, select CSharp Extension Method, and then click OK.

Example

The following image shows a static C# class, named ExtensionClass, containing the static method Times. The method takes in a parameter of type UML Integer to extend and another parameter of type UML Integer for the multiplier, and the method returns an integer back.
C# class ExtensionClass.

After a UML-to-C# transformation is run, the following code is generated:

//Begin section for file ExtensionClass.cs
//TODO: Add using directives that you want preserved
//End section for file ExtensionClass.cs

using System;

// @generated
public static class ExtensionClass
{

	// @generated
	public static Int32 Times(this Int32 typeParameter, Int32 multiplier)
	{
		//TODO: Auto-generated method stub
		throw new System.NotImplementedException();
	}
}

What to do next

After modeling the extension method, you can configure and run a UML-to-C# transformation to generate the C# code for the method.

Feedback