Page Comparison - 3.2 Creating Code Elements (v.1 vs v.2)

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

You're probably curious to know what the second parameter is. Essentially, the second parameter is an array of o object}}s which act in a similar way to the way the the {{args parameters act in a string.Format() call.

Why are these parameters needed? Well, interestingly enough, the parameters allow you to specify additional checks that need to be made during the generation of code. For example, let us suppose that we need to create a statement similar to int x = 0;, but the name of the variable is provided elsewhere. What would happen if that variable's name was int or event? Creating the statement would result in erroneous code.

...

Code Block
languagecsharp
int @event = 0;

The Type Factory

Creating types is an important task in the ReSharper ecosystem. For example, say you wanted to write a context action to implement change notification in a class. This would require you to create, say, an INotifyPropertyChanged interface type.

Types are created using the TypeFactory. There are many overloads for creating types. The simplest simply creates a type when provided the type's FQN (fully qualified name):

Code Block
languagecsharp
IDeclaredType propertyChangedInterface =
        TypeFactory.CreateTypeByCLRName("System.ComponentModel.INotifyPropertyChanged", provider.PsiModule);

Creating a generic type is a little bit more complicated. You first use the TypeElementUtil helper class to get the type element for the generic type. The 'backquote notation' is used for this, so that Lazy<T> effectively becomes Lazy`1. After you have received the type element, you call the TypeFactory method to create the type, providing first the type element you created, and then an array of types that specify the generic arguments:

Code Block
languagecsharp
var lazyTypeElem = TypeElementUtil.GetTypeElementByClrName(new ClrTypeName("System.Lazy`1"), psiModule);
var lazyType = TypeFactory.CreateType(lazyTypeElem, thisType);

Please note that if you want to use the type to create, e.g., statements with the $ notation, you cannot simply use the parameter of IDeclaredType - you need to call GetTypeElement() on it.