0

What is the difference between instantiating a variable inside constructor vs. outside in the class declaration, for example:

public class Test
{
    private decimal a = new decimal(1.0);
    private decimal b;
    public Test() { b = new decimal (1.0); }
}

I'm using 'decimal', but the question is a general one, is there a difference, or a preference as to which method should be used?

2

1 Answer 1

1

It doesn't matter for C#, just be consistent and use the same practice everywhere in your code.

If your are working with a team and your team is already using a standard practice follow it, otherwise decide what's best for yourself and go with it.

Just keep in mind that if you decide use the declaration, your variables will be initialized before the constructor.

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

Comments

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.