Create class fields from methods via Live Templates

Hello everyone,

I want to create a simple live template that will introduce a field in the belonging class from one of its methods. I wonder if it possible and if so how can I achieve this behavior? Thanks in advance :)

For example:

public class SomeClass
{
private int _somePrivateField;
public void SomeMethod()
{
// Create the _somePrivateField from here using live templates.
}
}

 

4 comments
Comment actions Permalink

Hi Murat Tuver

There is a `Initialize field from constructor` quick fix available. Is this what are you looking for? Please give me some more details if I misleading you. 

By the way, here are some tips on how to create live templates.

0
Comment actions Permalink

Sorry for the late reply :(

The snippet I shared is the result that I want to achieve. Here are the steps I want to follow to in order to achieve this behavior.

Say I created a method like the SomeMethod method. Then I want to use a live template that creates a field and prints it to the console from the method's context. 

Before inserting the live template:

public class SomeClass
{
public void SomeMethod()
{
// Cursor here
}
}

After inserting the live template:

public class SomeClass
{
private string _someStr;
public void SomeMethod()
{
Console.WriteLine(_someStr);
}
}

The problem I am facing is to create the class scoped field from the method scope. I hope I made it more clear :D

Thanks for your time!

0
Comment actions Permalink

Hi Murat Tuver

Thank you for the details. 

There are two ways. First is to use a regular "Create field" quick fix:

 

Second, if you want to generate all such a method at once, one can create a live template like this: 

private $type1$ $fieldName$
public $type2$ $name$()
  {
    Console.WriteLine($fieldName$);
    $END$
  }

`Create field` is not actually a live template, so I'm not sure this is possible to create code outside the scope with live templates for now. 

Please let me know if these ways are also not what you are looking for. We'll try to find another one :) 

0
Comment actions Permalink

I guess there is no way of reaching upper scopes in file templates. I will stick with 'Create Field' fix for now.

Thanks for the help :) 

0

Please sign in to leave a comment.