Access source generated class property/method in main code MSVS 2022

Viewed 129

I created my first source generator (ISourceGenerator) with public property and public method.

Let this class be like this:

public partial class MyClass1 // Manually written code
{
}

public partial class MyClass1 //Source Generated code
{
    public string GeneratedProperty { get; set; }
    public string GeneratedMethod() => "lala";
}

Both of these classes are located in the same namespace (for example, MyNamespace - it doesn't matter really).

So, I'm trying this:

var myClass = new MyClass1(); // Correct
Console.WriteLine(myClass.GeneratedMethod()); //Wrong, "MyClass1 doesn't contain definition for GeneratedMethod..."

When I say MSVS generate sources as files in the concrete directory, I have the code above working well.

So, I want to have an ability to use generated code "on fly" when I write code without generation source files each time manually. Also earlier manually generated source files are not deleted when I'm generating new source files. Is it possible?

Thank you.

UPD. I have this message from Visual Studio: "Warning CS8032 An instance of analyzer Generators.Factory.AbstractFactoryGenerator cannot be created from ...\bin\Debug\netstandard2.0\SourceGeneratorsLibrary.dll: Exception has been thrown by the target of an invocation." Maybe this significant?

UPD2. https://pastebin.com/qtvrugu3 - this is my Source Generator code. Pls, don't blame me, It's just my first steps.

1 Answers

As far as I know, programming is case sensitive, well at least C# so myClass() is different from MyClass(). also hence you are using the string data type, try casting it as string via

Convert.ToString(MyClass1().GeneratedMethod());

or

MyClass1().GeneratedMethod().ToString();

hope this answers you question.

Related