Jacob Pressures
Jacob Pressures

Reputation: 1461

In C# Both const and static member varables can:

This was an interview question I was asked. I wasn't sure about the answer.

In C# Both const and static member varables can:

A) Be set in a static constructor, static method, or instance method of a class.
B) Change after a class has been initialized the first time.
C) Only be set in an instance constructor.
D) Be accessed without an instance of a class.
E) Be set by a set accessor of a public property.

I chose "A" even though I was unsure what they meant. I didn't know whether to pick A or E. Since I was running out of time I picked A. I probably should have picked E.

A) My problem with this one is that it says "instance method."
B) They don't change - False
C) Is the constructor of a static method or class called an "Instance Constructor?" I know you can have a static constructor.
D) How can you access a constant without an instance? - FALSE
E) Not sure. I guess this could be true.

Can someone explain? thanks!

Upvotes: 0

Views: 1687

Answers (4)

code4life
code4life

Reputation: 15794

Quick breakdown of the answers:

A) False, since consts don't get set in the static constructor.

B) False, you can't change the value of a const after declaring it

C) False, again, can't set consts after declaring it. You can set static variables in an instance method (and ctors) but can't change a const once you define it.

D) True - you don't need an instance of the class in order to access either.

E) False, again, consts can't be changed...

Upvotes: 1

Rob
Rob

Reputation: 27357

In C# Both const and static member varables can:

A) Be set in a static constructor, static method, or instance method of a class.
B) Change after a class has been initialized the first time.
C) Only be set in an instance constructor.
D) Be accessed without an instance of a class.
E) Be set by a set accessor of a public property.

A) You can't ever set a constant, you can only define it. You can define a constant anywhere you can define a variable, but the very word set means this choice is wrong.

B) You definitely can't change a constant, so it's not B.

C) Incorrect, as above (A)

D) Fine, you can write MyClass.MyConst and MyClass.MyStatic

E) Incorrect, you can't change a constant.

So the answer is D.

Upvotes: 4

Philippe Paré
Philippe Paré

Reputation: 4408

The answer was D. Any constant or static member that is public, protected or internal can be accessed outside the class without an instance.

Think of a const as a value type static readonly variable. also, marking them as const lets the compile use optimization at compilation.

Upvotes: 2

nickm
nickm

Reputation: 1775

The answer is D.

A static member or property and a const can be accessed without an instance.

i.e

var x = Foo.StaticProperty;

Think of const as a static value that can not be changed at runtime.

E is incorrect because you cannot set a const at all.

Upvotes: 1

Related Questions