0

In my application, I've got a class which I would like to behave like a value type whenever copied:

    public class SpecialId 
    {
        private int internalValue;
        public SpecialId(int id)
        {
          internalValue = id;
        }

        //integer conversions
        public static implicit operator SpecialIdint index) => new SpecialId(index);
        public static implicit operator int(SpecialId obj) => obj.internalValue;
    }

(This type is really just an integer, but I want to do this so that any routine that is expecting a SpecialId will cause a compiler error if I pass it SomeOtherKindOfId.)

Because I want this to behave like an integer, I'd like it to work so that if I write

var copiedId = mySpecialId

then copiedId will be a value copy, not a reference copy, as you would have with an integer.

Is this possible?

(I know I could use a struct instead, but there are some unrelated reasons why I don't think I can do this.)

Edit: The reason I don't want to use a struct is that this class is actually inheriting from a base class that does a bunch of things to support this usage, such as implementing Object.Equals, Object.ToString, and the like, so that I can have multiple instances of them without repeating a ton of boilerplate code. But you can't have an inherited struct in c#, so I'm using a class here.

Joshua Frank
  • 12,514
  • 11
  • 45
  • 90
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/235495/discussion-on-question-by-joshua-frank-is-it-possible-to-implement-a-c-class-wi). – Machavity Jul 31 '21 at 20:33

0 Answers0