Bird
Raised Fist0

You want to count how many objects of a class are created, but also keep a unique ID for each object starting from 1. Which approach correctly uses static and instance members?

hard🚀 Application Q15 of Q15
C Sharp (C#) - Classes and Objects
You want to count how many objects of a class are created, but also keep a unique ID for each object starting from 1. Which approach correctly uses static and instance members?
AUse only instance fields for both counter and ID.
BUse an instance counter incremented in constructor; assign its value to a static ID field.
CUse a static counter incremented in constructor; assign its value to an instance ID field.
DUse static fields for both counter and ID without instance fields.
Step-by-Step Solution
Solution:
  1. Step 1: Understand counting objects with static field

    A static counter shared by all objects can track total created objects.
  2. Step 2: Assign unique ID per object using instance field

    Each object gets its own instance ID assigned from the static counter value.
  3. Final Answer:

    Use a static counter incremented in constructor; assign its value to an instance ID field. -> Option C
  4. Quick Check:

    Static counter + instance ID = unique IDs [OK]
Quick Trick: Static counts total; instance stores unique ID per object [OK]
Common Mistakes:
MISTAKES
  • Using instance counter for total count
  • Assigning static ID per object (not unique)
  • Not incrementing counter in constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes