-1

Suppose I have a class Foo like below:

class Foo
{
    public static int Bar()
    {
        return 1;
    }

    public static int x = Bar();
    public static int y = 2;
}

I want to use reflection to know that:

  1. x is initialized via the function Bar.
  2. y isn't initialized via the function Bar.

Is there any way to do this?

Caesium
  • 789
  • 3
  • 7
  • 24
  • The real question is why? You are in control of this logic implicitly – TheGeneral Nov 14 '18 at 05:30
  • The reason is complex, the original problem I need to solve is that: in our code base, we have a complex class `P` and a static method `CreateP` which returns an instance of `P` (`P` can also created by other methods), now we want to lock down the usage of `CreateP` so that no more `P` is added via `CreateP`, meanwhile, the original `P` created by `CreateP` and the parameters passed to `CreateP` shouldn't change any more. I will do this by adding a unit test to the code base. So I want to scan all the assemblies to get all the `P` and find out the `P`s created by `CreateP`. – Caesium Nov 14 '18 at 05:54
  • 3
    It does sound complex, however i would just mark the static creator with [Obsolete] which would bug the other developers enough not to use it, and also make them refactor it out to stop the warnings and underlines – TheGeneral Nov 14 '18 at 06:01
  • Code code still call `CreateP` and that should not trigger warning. But the newly added code (from the time I lock it down) should not work. – Caesium Nov 14 '18 at 06:05
  • 1
    You may need to rethink your problem, there is not easy way to do what you want, and even if you could, it would probably be more hassle than its worth, just refactor the code maybe – TheGeneral Nov 14 '18 at 06:07
  • If I was being pedantic (and I am!), I would highlight that `x` and `y` are **fields** not properties. – mjwills Nov 14 '18 at 07:08
  • 1
    Yes, so you mark the method as `[Obsolete]`, then suppress this warning at each existing call site. Then those usages won't trigger the warning any more but any new call sites will. – Damien_The_Unbeliever Nov 14 '18 at 08:02

1 Answers1

0

Sorry but none of your properties are created from your function Bar anyway.Are you talking about initialization and or when/where are they assigned? Please clarify your question.

A similar question was asked here: When do static variables get initialized in C#?

EDIT

Based on the new information you can change Access Modifiers or utilize the [Obsolete] attribute: https://learn.microsoft.com/en-us/dotnet/api/system.obsoleteattribute?view=netframework-4.7.2 to control or restrict creation.

Tomek
  • 323
  • 1
  • 4
  • 19
  • Yes, it's **initialization** by `Bar`. And I think the question is find out all the properties `initialized` by `Bar`. – Caesium Nov 14 '18 at 06:03
  • 1
    in your code example your `Bar` function does not initialize anything, it returns a value.You assign this value then to `x`. – Tomek Nov 14 '18 at 06:09