Limited Object type in .NET

Let's have a library of objects Person, Cat, Dog, Pencil and Byke.

Let's give to Person a FavoriteThing member, that can be of any of listed types.

Let's imagine that we have to save the Person's state using a serialization, so we make all of listed objects as Serializable.

How do we now protect the Person from "injecting" him a "FavoriteThing" like Cobra class, that does not comply the requirements (to be Serializable, or others, like to be inoffensive :).


You might want to write a FavoriteThing type which acts as a tagged union. In other words, it has a property for each type (person, cat etc) but enforces that it only contains one value at a time. You may not explicitly need a tag field if these are all reference types; just make sure that only one of your strongly-typed fields is non-null at a time. You will need to provide a way of determining which type has a value though.

Another option is to make all of those types implement a common interface - but that may not be an appropriate design, if those types shouldn't really know about the "favorite" concept.

It's hard to be more concrete without knowing what you'd want to do with the favorite thing...

I am not sure exactly what you want to achieve, but if you in some way want to be able to define what types should be allowed to be assigned to FavoriteThing, you could create an empty interface (let's call it IFavorable), and declare FavoriteThing as being of that type;

public interface IFavorable { }

class Person
    public IFavorable FavoriteThing { get; set; }

Then you make the allowed types "implement" this interface:

class Dog : IFavorable
    // ...

That would work, though I am not a huge fan of such "meta interfaces" myself...

Need Your Help

`EXC_BAD_ACCESS` in Class implementing KVO

ios objective-c key-value-observing

Objective-c noob here. I'm experiencing a EXC_BAD_ACCESS error in my tests and can't figure out why. I've written a Cart class for my application representing a user's cart. A Cart can have multiple

postion icons within LinearLayout

android android-layout view android-linearlayout

I've an app where i have 2 icons within a Linearlayout. I'm not particularly good with layouts and i'm unsure how to position the icons next to each other centrally. Could anyone explain how i can do

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.