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 6348307
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T21:23:38+00:00 2026-05-24T21:23:38+00:00

Suppose I have an immutable value type like this: [Serializable] [DataContract] public struct MyValueType

  • 0

Suppose I have an immutable value type like this:

[Serializable]
[DataContract]
public struct MyValueType : ISerializable
{
private readonly int _x;
private readonly int _z;

public MyValueType(int x, int z)
    : this()
{
    _x = x;
    _z = z;
}

// this constructor is used for deserialization
public MyValueType(SerializationInfo info, StreamingContext text)
    : this()
{
    _x = info.GetInt32("X");
    _z = info.GetInt32("Z");
}

[DataMember(Order = 1)]
public int X
{
    get { return _x; }
}

[DataMember(Order = 2)]
public int Z
{
    get { return _z; }
}

public static bool operator ==(MyValueType a, MyValueType b)
{
    return a.Equals(b);
}

public static bool operator !=(MyValueType a, MyValueType b)
{
    return !(a == b);
}

public override bool Equals(object other)
{
    if (!(other is MyValueType))
    {
        return false;
    }

    return Equals((MyValueType)other);
}

public bool Equals(MyValueType other)
{
    return X == other.X && Z == other.Z;
}

public override int GetHashCode()
{
    unchecked
    {
        return (X * 397) ^ Z;
    }
}

// this method is called during serialization
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
    info.AddValue("X", X);
    info.AddValue("Z", Z);
}

public override string ToString()
{
    return string.Format("[{0}, {1}]", X, Z);
}
}

It works with BinaryFormatter or DataContractSerializer but when I try to use it with protobuf-net (http://code.google.com/p/protobuf-net/) serializer I get this error:

Cannot apply changes to property
ConsoleApplication.Program+MyValueType.X

If I apply setters to the properties marked with DataMember attribute it will work but then it breaks immutability of this value type and that’s not desirable to us.

Does anyone know what I need to do to get it work? I’ve noticed that there’s an overload of the ProtoBu.Serializer.Serialize method which takes in a SerializationInfo and a StreamingContext but I’ve not use them outside of the context of implementing ISerializable interface, so any code examples on how to use them in this context will be much appreciated!

Thanks,

EDIT: so I dug up some old MSDN article and got a better understanding of where and how SerializationInfo and StreamingContext is used, but when I tried to do this:

var serializationInfo = new SerializationInfo(
    typeof(MyValueType), new FormatterConverter());
ProtoBuf.Serializer.Serialize(serializationInfo, valueType);

it turns out that the Serialize<T> method only allows reference types, is there a particular reason for that? It seems a little strange given that I’m able to serialize value types exposed through a reference type.

  • 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-24T21:23:39+00:00Added an answer on May 24, 2026 at 9:23 pm

    Which version of protobuf-net are you using? If you are the latest v2 build, it should cope with this automatically. In case I haven’t deployed this code yet, I’ll update the download areas in a moment, but essentially if your type is unadorned (no attributes), it will detect the common “tuple” patten you are using, and decide (from the constructor) that x (constructor parameter)/X (property) is field 1, and z/Z is field 2.

    Another approach is to mark the fields:

    [ProtoMember(1)]
    private readonly int _x;
    
    [ProtoMember(2)]
    private readonly int _z;
    

    (or alternatively [DataMember(Order=n)] on the fields)

    which should work, depending on the trust level. What I haven’t done yet is generalise the constructor code to attributed scenarios. That isn’t hard, but I wanted to push the basic case first, then evolve it.

    I’ve added the following two samples/tests with full code here:

        [Test]
        public void RoundTripImmutableTypeAsTuple()
        {
            using(var ms = new MemoryStream())
            {
                var val = new MyValueTypeAsTuple(123, 456);
                Serializer.Serialize(ms, val);
                ms.Position = 0;
                var clone = Serializer.Deserialize<MyValueTypeAsTuple>(ms);
                Assert.AreEqual(123, clone.X);
                Assert.AreEqual(456, clone.Z);
            }
        }
        [Test]
        public void RoundTripImmutableTypeViaFields()
        {
            using (var ms = new MemoryStream())
            {
                var val = new MyValueTypeViaFields(123, 456);
                Serializer.Serialize(ms, val);
                ms.Position = 0;
                var clone = Serializer.Deserialize<MyValueTypeViaFields>(ms);
                Assert.AreEqual(123, clone.X);
                Assert.AreEqual(456, clone.Z);
            }
        }
    

    Also:

    it turns out that the Serialize method only allows reference types

    yes, that was a design limitation of v1 that related to the boxing model etc; this no longer applies with v2.

    Also, note that protobuf-net doesn’t itself consume ISerializable (although it can be used to implement ISerializable).

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

Sidebar

Related Questions

Suppose we have a function like this one: foo (x, _, y) = (x,
Suppose i have an XML file, that i use as local database, like this):
Let's suppose that I have the following class which tries to be immutable public
If I have a deeply immutable type (all members are readonly and if they
Suppose I have a namedtuple like this: EdgeBase = namedtuple(EdgeBase, left, right) I want
Suppose I have a stringbuilder in C# that does this: StringBuilder sb = new
Suppose I have BaseClass with public methods A and B, and I create DerivedClass
Suppose I have this array: $array = array('10', '20', '30.30', '40', '50'); Questions: What
Suppose I have an immutable NSArray and want to create several sub-arrays. I could
Suppose I have a class with a collection of immutable types, that I would

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.