12

I run sgen against my assembly with a metric ton of types. I want to exclude 2 types from serialization. I don't seem to be able to find a way to do it.

I see that sgen has a /type switch to specify a specific type, but nothing to exclude a specific type.

Is there a way to exclude specific types from serialization?

AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • 1
    Maybe I didn't understand your question, but `sgen` only generates the serialization assembly. What is the problem with having another two classes in there? – Hanan M Feb 03 '13 at 22:41
  • 1
    In case you want to do this because SGEN complains about identical class names, then open your .csproj file and you may find `false` tags. I removed those while leaving `On` alone and the errors went away. – Louis Somers Apr 23 '20 at 13:41

4 Answers4

3

Apart from putting the types you wish to exclude in a different assembly, you cannot exclude types from the serializer generation.

Update

Other posters have come up with additional possibilities to exclude specific types, with varying applicability based on your use case.

tm1
  • 1,180
  • 12
  • 28
  • 1
    I know this is old. But what about removing parameter less constructor? That appears to prevent sgen processing class. – Tom Jul 22 '19 at 18:10
  • @Tom Yes, this works for me. Consider posting a respective answer - I'll upvote. – tm1 Jul 23 '19 at 10:59
1

You can try changing the access of the classes you want to exclude from Xml Serialization by marking the class as internal, then sgen.exe should skip that class.

internal class NotToBeSerialized
{
    ...
}
Mikael Engver
  • 4,634
  • 4
  • 46
  • 53
1

To prevent the class being included in sgen processing, ensure it doesn't have a parameterless constructor.

As explained by the answer to this question Why XML-Serializable class need a parameterless constructor, serialization requires a parameter less constructor, of any permission level, to work. Making the paramaterless constructor private isn't sufficient, to exclude if from sgen processing.

Tom
  • 6,325
  • 4
  • 31
  • 55
-6

Not sure if you are looking for this but you can exclude your own classes from serialization by mentioning [NonSerialized] before class definition. So if you want to exclude a specific type you will have to inherit from it and create your own class

[NonSerialized]
public class Point
{
    public int x, y;
}
Mohsen Sarkar
  • 5,910
  • 7
  • 47
  • 86
  • 2
    This code should not compile, because the `NonSerialized` attribute's only targets are fields. – tm1 Apr 15 '13 at 07:14
  • 1
    Error 2 Attribute 'NonSerialized' is not valid on this declaration type. It is only valid on 'field' declarations. – Ryan Williams Sep 25 '14 at 04:52