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.

4
  • 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 Commented Nov 1, 2016 at 9:36
  • 8
    What would that even mean? The instance fields don't exist until there's an object of that type. Commented Nov 1, 2016 at 9: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?) :) Commented Nov 1, 2016 at 9:39
  • yeah that is true. I will probably find another way to test the class. Thanks! Commented Nov 1, 2016 at 9:51

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.