• 0

<C#> Inheriting from List<>


Question

I am trying to inherit from List<Blah> so essentially I have something like this:

class Foo : List<Blah>

{

...

private string _var1;

private string _var2;

public string Var1

{

get { return _var1; }

}

public string Var2

{

get { return _var2; }

}

...

}

Now the problem is when I go to serialize this I get back only a representation of the inherited List properties (the collection of Blah objects) and nothing in the Foo class like Var1 and Var2. If I pull the List<Blah> down into the class instead of inheriting from it, there are no issues. What is causing the serializer to miss the public properites of the Foo class?

Thanks and regards

Link to comment
https://www.neowin.net/forum/topic/496842-c-inheriting-from-list/
Share on other sites

5 answers to this question

Recommended Posts

  • 0

First, what serializer are you using? XML? Binary?

If you're using an XmlSerializer, have you tried adding serialization attributes to your properties? The serializer may not serialize get-only properties by default:

[XmlElement("Var1Element")]
public String Var1
{
   get {return _var1;}
}

If you're using a binary serializer, you need to mark your class (inheriting from a serializable base class may not good enough) with the SerializableAttribute, and inherit from the ISerializable interface if you require control over serialization.

  • 0
  dannysmurf said:

First, what serializer are you using? XML? Binary?

If you're using an XmlSerializer, have you tried adding serialization attributes to your properties? The serializer may not serialize get-only properties by default:

[XmlElement("Var1Element")]
public String Var1
{
   get {return _var1;}
}

If you're using a binary serializer, you need to mark your class (inheriting from a serializable base class may not good enough) with the SerializableAttribute, and inherit from the ISerializable interface if you require control over serialization.

Thanks for your reply. I am using the XmlSerializer and although I did not place a set in the example code, there is indeed one there. Applying the XmlElement attribute was unsuccessful.

Complete example non-working code:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

public class Foo : List&lt;Blah&gt;
{
	public Foo()
	{
	}

	public Foo(string var1, string var2)
	{
		_var1 = var1;
		_var2 = var2;
	}

	private string _var1;
	private string _var2;

	[XmlElement("Var1")]
	public string Var1
	{
		get { return _var1; }
		set { _var1 = value; }
	}

	[XmlElement("Var2")]
	public string Var2
	{
		get { return _var2; }
		set { _var2 = value; }
	}

	public string ToXML()
	{
		return UtilTesting.GetXML(this);
	}
}

public class Blah
{
	public Blah()
	{

	}

	public Blah(string word, int number)
	{
		_word = word;
		_number = number;
	}

	private string _word;
	private int _number;

	public string Word
	{
		get { return _word; }
		set { _word = value; }
	}

	public int Number
	{
		get { return _number; }
		set { _number = value; }
	}
}

public class UtilTesting
{
	public static string GetXML(object obj)
	{
		XmlDocument retVal = new XmlDocument();
		//Convert the obj into an Xml document
		XmlSerializer ser = new XmlSerializer(obj.GetType());
		StringBuilder sb = new StringBuilder();
		TextWriter writer = new StringWriter(sb);
		ser.Serialize(writer, obj);

		return sb.ToString();
	}
}

Use it as follows:

   Foo test = new Foo("Test", "Testing");
   test.Add(new Blah("One", 1));
   test.Add(new Blah("Two", 2));
   string xml = test.ToXML();

  • 0

I found this on MSDN for the XmLSerializer class.

  Quote
Only collections are serialized, not public properties.

I dont really understand it because when i take out the List<Blah> inherit from foo and the " test.Add(new Blah("One", 1));" in main i get

&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">lt;Var1&gt;Test&lt;/Var1&gt;
  &lt;Var2&gt;Testing&lt;/Var2&gt;
&lt;/Foo&gt;

..... might want to post this in the MSDN forms

  • 0
  dolimite35 said:

I found this on MSDN for the XmLSerializer class.

I dont really understand it because when i take out the List<Blah> inherit from foo and the " test.Add(new Blah("One", 1));" in main i get

&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">lt;Var1&gt;Test&lt;/Var1&gt;
  &lt;Var2&gt;Testing&lt;/Var2&gt;
&lt;/Foo&gt;

..... might want to post this in the MSDN forms

Thanks for you input. I have made a similar post on the MSDN forums...for anyone interested: http://forums.microsoft.com/MSDN/ShowPost....46&SiteID=1

  • 0

I found an answer although I wish it was a better one. Basically when inheriting from a list or any collection for that matter, public properties are not serialized because the collection is treated as an array and not an object. The article can be found here: http://forums.microsoft.com/MSDN/ShowPost....46&SiteID=1

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • OK Microsoft, can you please fire the entire Windows team and hire those 20 Xbox developers instead to work on Windows? We'd all pretty much want to have a light and bloat free Windows!
    • Call of Duty: Black Ops 7 is out this year, landing with a "mind-bending" co-op campaign by Pulasthi Ariyasinghe A surprise Call of Duty announcement landed during the Xbox Game Showcase event today, with Treyarch and Raven Software unveiling Call of Duty: Black Ops 7 as the next entry in the massively popular FPS franchise. While many were expecting the 2025 entry to be a Modern Warfare game, this will be the first time in the history of the series that two Black Ops games will be releasing back to back. Watch the teaser trailer above. Black Ops 7 will be set 40 years after the events of Black Ops 6, taking players to 2035 for a more futuristic experience. "Wielding cutting-edge technology, David Mason and his team must fight back against a manipulative enemy who weaponizes fear above all else," says the company. "The Black Ops universe is amazing. The creativity and imagination that goes into the storytelling, the rich character depth, and the incredible moment-to-moment gameplay across all modes is really exceptional," says Matt Cox, General Manager of Call of Duty. "As a team, our vision from the start was to create a back-to-back series experience for our players that embraced the uniqueness of the Black Ops sub-franchise." In another twist, the complete campaign will be playable in co-op in addition to offering solo play like usual. The story will follow a world that's on the brink of chaos, according to Treyarch, where violent conflicts and psychological warfare are rampant. Of course, a complete multiplayer portion with new maps and weapons, as well as another dose of round-based Zombies in the Dark Aether will be included in the package too. The complete reveal for Call of Duty: Black Ops 7 will be releasing later this year before the full launch The title is coming to PC, Xbox Series X|S, Xbox One, PlayStation 5, and PlayStation 4. Game Pass subscribers are gaining access on day one too.
    • Indiana Jones and the Great Circle: The Order of Giants DLC launches this September by Pulasthi Ariyasinghe The Xbox Games Showcase gave a look at the next Indiana Jones adventure today. MachineGames showed up with a trailer for the first DLC pack coming to Indiana Jones and the Great Circle: The Order of Giants. Set in Italy, the fresh story will introduce new locations, puzzles, enemies and more. Watch the reveal trailer above. This Indy journey will be taking place during the main campaign and dive deeper into the tribe of giants, Nephilim Order, that players see in the base game. The story will kick off with Indiana Jones offering help to a young priest named Father Ricci, who is attempting to track down a mysterious artifact. The resulting journey expands into this separate storyline that takes the player beyond Vatican City to explore Rome's streets and the crypts beneath it. “One of the most satisfying parts of developing Indiana Jones and the Great Circle was the opportunity to create the Nephilim Order, the secret society of giants formed by descendants of fallen angels working to atone for their ancestral sins,” says Production Director John Jennings. “That story spans thousands of years and this DLC has given us the opportunity to develop further upon their lore and look at other aspects not covered in the initial story campaign. There’s something new and unexpected to tell here for fans of the game, and we can’t wait for people to be able to play it for themselves.” The Indiana Jones and the Great Circle: The Order of Giants DLC will be releasing on September 4, 2025. It will be available on PC, Xbox Series X|S, and PlayStation 5. Premium Edition, Premium Upgrade, Collector’s Edition, and Collector’s Bundle owners will be receiving the DLC for no extra charge at launch.
    • Could we have a desktop version of this lightweight bloat free Windows 11?
    • So they admit that Windows 11 is slow and bloated. Good to know!
  • Recent Achievements

    • Dedicated
      Epaminombas earned a badge
      Dedicated
    • Veteran
      Yonah went up a rank
      Veteran
    • First Post
      viraltui earned a badge
      First Post
    • Reacting Well
      viraltui earned a badge
      Reacting Well
    • Week One Done
      LunaFerret earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      474
    2. 2
      +FloatingFatMan
      265
    3. 3
      ATLien_0
      235
    4. 4
      snowy owl
      228
    5. 5
      Edouard
      174
  • Tell a friend

    Love Neowin? Tell a friend!