Overloads with usage location restriction - for source generation scenarios #3987
Replies: 4 comments 12 replies
-
Sounds like something you can accomplish with a custom analyzer. |
Beta Was this translation helpful? Give feedback.
-
Can you think of any scenarios where this would be useful other than for this very specific scenario? In most cases I think CallerMemberNameAttribute should be sufficient. Also note your current design wouldn't work if there were multiple calls to log in the same method. That seems quite limited. |
Beta Was this translation helpful? Give feedback.
-
Generally, you can already attempt to do this today with the "hide-to-rewrite" approach many source generation scenarios take to "rewrite" user code.
[CustomLogRewrite]
static void Method1Core(int p1)
{
int v1 = 15;
int v2 = Calc1();
logger.Log(p1, v1, v2);
}
static void Method1(int p1)
{
int v1 = 15;
int v2 = Calc1();
logger.WriteLine($"Method: Method1, p1 parameter: {p1}, v1 variable: {v1}, v2 variable (result of calling Calc1): {v2}");
}
Of course it's neither pretty nor expandable (you can only have one generator "overwrite" your method), but it's something you can do today. |
Beta Was this translation helpful? Give feedback.
-
In your post, you say that the second scenario no longer applies. So it sounds like there is a solution for the first scenario already possible with our CallerXxx attributes. |
Beta Was this translation helpful? Give feedback.
-
Consider the following non-generated code:
And the following generated code (by a source generator):
This allows a special implementation for each invocation of Log based on the "environment" of the invocation. Even if the parameter names and types are the same for two invocations, we can generate two extension classes each with one extension method. Because of the OverloadRestrictedTo attribute, the compiler has no problem knowing which overload to use.
UPDATE: I discovered that the following is not really a usage scenario for the suggested feature (it can be done with source generators alone). Please ignore it. I keep it to make comments below understandable.
As another usage scenario, this can also be used to return concrete types for different input types, e.g.:
For example, this can be used with fakes in unit testing:
Beta Was this translation helpful? Give feedback.
All reactions