Search code examples
c#constructorpropertiesroslync#-6.0

How do I use a property to initialize another property?


Why is this:

public int X { get; } = 5
public int Y { get; } = X;

not possible?

Because doing it manually:

public TestClass()
{
  X = 5;
  Y = X;
}

Works, and so does (obviously?) this:

public static int X { get; } = 5;
public static int Y { get; } = X;

Is there a way to get the first example to compile, or do I have to do it manually in the ctor?

(My real problem is far more complex, not just ints, but instances that are then being used to create other instances, but this example is easier to discuss)


Solution

  • The reason why this is not possible is that these initializations are done before the constructor is called. So it happens in a static context. The object is not yet fully initialized and there is no this reference yet. So you cannot access a non-static property like X.

    For the same reason it works for the static properties in your third example.

    So I don't see a workaround but doing this kind of initialization in a constructor.