0

I am inexperience with c# and I would like to ask if there is any way to access non-static fields without creating an object?

I am unit testing a program(so I can't change the way the class is written) and my aim is to get the initialised values of the fields. The problem here is that the constructor changes some of the field values.

I would highly appreciate any suggestions.

Angelo Charl
  • 347
  • 4
  • 15
  • Although it's not quite what you want, you could have two constructors, which are overloaded - and then when you need the original values call the second constructor which would modify no values – Alfie Goodacre Nov 01 '16 at 09:36
  • 8
    What would that even mean? The instance fields don't *exist* until there's an object of that type. – Jon Skeet Nov 01 '16 at 09:36
  • 1
    Can you pet a dog without a dog? :) Answering your `constructor changes some fields` question: it's how programming works. If a programmer has decided to make this class work this way, then you need to work with it. If it seems inapropriate or untestable, you need to tell it to your developer (or yourself?) :) – Yeldar Kurmangaliyev Nov 01 '16 at 09:39
  • yeah that is true. I will probably find another way to test the class. Thanks! – Angelo Charl Nov 01 '16 at 09:51

2 Answers2

1

It's impossible, since non-static fields by definition belong to a certain object. However, there's a way to create an object without calling its constructors - see this question.

Community
  • 1
  • 1
stop-cran
  • 4,229
  • 2
  • 30
  • 47
1

There is no way to access non-static fields without creating an object.

The only way to achieve your goal is to write a constructor that does not do the changes.

Although on a second thought: If the changes are part of the constructor, then it does not make sense to me to check for the initial values. From the perspective of the client objects using the objects of this class, these changes have no effect, because the constructor will be executed completely before this object can be called.

Ralf Bönning
  • 14,515
  • 5
  • 49
  • 67
  • well, there are several constructors and each one of them do slightly different things. And on top of that, the way the fields are altered are based from external fields. so it is not like it is initialised in a fixed value. – Angelo Charl Nov 01 '16 at 09:49