Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3309190
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T21:36:40+00:00 2026-05-17T21:36:40+00:00

Reviewing an earlier question on SO, I started thinking about the situation where a

  • 0

Reviewing an earlier question on SO, I started thinking about the situation where a class exposes a value, such as a collection, as an interface implemented by the value’s type. In the code example below, I am using a List, and exposing that list as IEnumerable.

Exposing the list through the IEnumerable interface defines the intent that the list only be enumerated over, not modified. However, since the instance can be re-cast back to a list, the list itself can of course be modified.

I also include in the sample a version of the method that prevents modification by copying the list item references to a new list each time the method is called, thereby preventing changes to the underlying list.

So my question is, should all code exposing a concrete type as an implemented interface do so by means of a copy operation? Would there be value in a language construct that explicitly indicates “I want to expose this value through an interface, and calling code should only be able to use this value through the interface”? What techniques do others use to prevent unintended side-effects like these when exposing concrete values through their interfaces.

Please note, I understand that the behavior illustrated is expected behavior. I am not claiming this behavior is wrong, just that it does allow use of functionality other than the expressed intent. Perhaps I am assigning too much significance to the interface – thinking of it as a functionality constraint. Thoughts?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TypeCastTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // Demonstrate casting situation
            Automobile castAuto = new Automobile();

            List<string> doorNamesCast = (List<string>)castAuto.GetDoorNamesUsingCast();

            doorNamesCast.Add("Spare Tire");

            // Would prefer this prints 4 names, 
            // actually prints 5 because IEnumerable<string>
            // was cast back to List<string>, exposing the 
            // Add method of the underlying List object
            // Since the list was cast to IEnumerable before being
            // returned, the expressed intent is that calling code
            // should only be able to enumerate over the collection,
            // not modify it.
            foreach (string doorName in castAuto.GetDoorNamesUsingCast())
            {
                Console.WriteLine(doorName);
            }

            Console.WriteLine();

            // --------------------------------------

            // Demonstrate casting defense
            Automobile copyAuto = new Automobile();

            List<string> doorNamesCopy = (List<string>)copyAuto.GetDoorNamesUsingCopy();

            doorNamesCopy.Add("Spare Tire");

            // This returns only 4 names,  
            // because the IEnumerable<string> that is 
            // returned is from a copied List<string>, so 
            // calling the Add method of the List object does
            // not modify the underlying collection
            foreach (string doorName in copyAuto.GetDoorNamesUsingCopy())
            {
                Console.WriteLine(doorName);
            }

            Console.ReadLine();
        }
    }

    public class Automobile
    {
        private List<string> doors = new List<string>();
        public Automobile()
        {
            doors.Add("Driver Front");
            doors.Add("Passenger Front");
            doors.Add("Driver Rear");
            doors.Add("Passenger Rear");
        }

        public IEnumerable<string> GetDoorNamesUsingCopy()
        {
            return new List<string>(doors).AsEnumerable<string>();
        }
        public IEnumerable<string> GetDoorNamesUsingCast()
        {
            return doors.AsEnumerable<string>();
        }
    }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T21:36:41+00:00Added an answer on May 17, 2026 at 9:36 pm

    One way you can prevent this is by using AsReadOnly() to prevent any such nefariousness. I think the real answer is though, you should never be relying on anything other than the exposed interface/contract in terms of the return types, etc. Doing anything else defies encapsulation, prevents you from swapping out your implementations for others that don’t use a List but instead just a T[], etc, etc.

    Edit:

    And down-casting like you mention is basically a violation of the Liskov Substition Principle, to get all technical and stuff.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

When reviewing, I sometimes encounter this kind of loop: i = begin while (
When reviewing our codebase, I found an inheritance structure that resembles the following pattern:
I am reviewing a big java application to see if there are any performance
I was reviewing some SQL queries and I saw a select statement that looked
I'm code reviewing a change one of my co-workers just did, and he added
I'm reviewing some code for a friend and say that he was using a
I am reviewing the flags we have for our MSVC projects, and I can't
I was just reviewing some old code and found the following (inside foo.asp): Const
I recall reviewing someone else's PHP code once and he had a function or
Without spending a long time reviewing the boost source code, could someone give me

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.