Terence Terence - 10 days ago 5
C# Question

Serializable with IEnumerable Property and a List Member

Today I found a gem in our codebase...

[Serializable]
public class MonsterClass
{
// Interfaces are good, especially for testing
public IEnumerable<FooBar> FooBars
{
get { return m_FooBars; }

// rationale = clever linq performance trick/safeguard
set { m_FooBars = new List(value); }
}

// alas ... it is serializable, thus we REQUIRE, it to be a List
private List<FooBar> m_FooBars;

//...
//ton loads of methods, performing tricks on list of FooBar and other types
//...
}


I want to refactor this monsterclass, by removing all the methods performed on
IEnumerable<FooBar> into a new FooBarList class.

Question: Would something of the following, be a safe replacement? While it still can be serialized!

[Serializable]
public class FooBarList : List<FooBar>, IEnumerable<FooBar>
{
public FooBarList(IEnumerable<FooBar> fooBars)
{
this = new List<FooBar>(fooBars);
}

//move specific methods here
}

[Serializable]
public class MonsterClass
{
public FooBarList FooBars { get; set; }

//still monsterclass, but now the FooBars are refactored out
}


Or is it a better idea, and take the lazy/chicken way out, by using extension methods?
(sidenote: I am ruling out the option of refactoring this class, by adding a domain model and adapter inbetween both of these, due to performance impact and refactoring time)

Answer

In this specific case, instead of using Composition, the best alternative is by using an extension method on IEnumerable<FooBar>