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

  • SEARCH
  • Home
  • 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 8483525
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T20:07:44+00:00 2026-06-10T20:07:44+00:00

I have a Generic class that takes an object of type T, serializes it

  • 0

I have a Generic class that takes an object of type T, serializes it as XML, then saves it to the filesystem. Currently however the serialize operation fails if the object is not serializable. That’s not a problem as such, however I think it would be better to check in my class constructor whether an instance of T is serializable or not and if it is not, throw an error at that point rather than later on.

Is there a way of checking of an instance of T can be serialized as XML other than simply instantiating it and trying to serialize it in a TRY…CATCH? It would be nice if I could interrogate the class T in some manner to discover whether it can be serialized as XML or not.

If it helps, the code can be seen here: http://winrtstoragehelper.codeplex.com/SourceControl/changeset/view/ac24e6e923cd#WinRtUtility%2fWinRtUtility%2fObjectStorageHelper.cs

Note that this code gets compiled against WinRT (i.e., it is for use in a Windows 8 app) however I think the question is relevant to any dialect of C#.

thanks in advance

Jamie

  • 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-06-10T20:07:45+00:00Added an answer on June 10, 2026 at 8:07 pm

    AFAIK, even if you check for various attributes (Serializable, DataContract) or check for the Type.IsSerializable (which I believe is just a convenience method for checking the Serializable attribute’s existence) it doesn’t guarantee that the implementation actually is serializable. (EDIT: As mentioned, and seen in the example code provided in the question, XmlSerializer does not depend on the Serializable attribute adornment. So there’s no sense in checking for these flags.)

    In my experience, your best bet is to use unit tests that will validate the various types used in your application and use try/catch to see if it pass/fails. At runtime, use try/catch (rather than pre-checking each time) and log/handle the exception.

    If you have a list of valid compatible types as a result of your unit-testing, you can have a pre-check of T against a compile-time list that you determined from testing previously and assume any other types are just no good. Might want to watch for subclasses of known valid types though as even if they inherit from a valid serializable type, their implementation may not be.

    EDIT: Since this is for Windows Phone 8, while I don’t have experience with that platform, I have worked with Silverlight. And in that case, you can serialize objects even if they are not marked as [Serializable] (in fact, it doesn’t even exist in Silverlight). The built-in XmlSerializer just works against all public properties regardless of adornment. The only way to see if it’s serializable is either attempt a serialization and try/catch the failure, or write an algorithm to inspect each property (and recursively through child objects) and check if each type can be serialized.

    EDITx2: Looking at your ObjectStorageHelper, I would suggest that you simply attempt serialization and catch any failures. You don’t necessarily have to bubble up the exception directly. You could wrap with your own custom exception or have a returned results object that informs the API consumer of the pass/fail of the serialization and why it may have failed. Better to assume the caller is using a valid object rather than doing an expensive check each time.

    EDITx3: Since you’re doing a lot of other work in the save method, I would suggest rewriting your code like this:

    public async Task SaveAsync(T Obj)
    {
        if (Obj == null)
            throw new ArgumentNullException("Obj");
    
        StorageFile file = null;
        StorageFolder folder = GetFolder(storageType);
        file = await folder.CreateFileAsync(FileName(Obj), CreationCollisionOption.ReplaceExisting);
    
        IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite);
        using (Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result)
        {
            try
            {
                serializer.Serialize(outStream, Obj);
            }
            catch (InvalidOperationException ex)
            {
                throw new TypeNotSerializableException(typeof(T), ex);
            }
    
            await outStream.FlushAsync();
        }
    }
    

    This way you catch the serialization issue specifically and can report to the API consumer very clearly that they have provided an invalid/non-serializable object. This way if you have an exception being thrown as part of your I/O portions, it’s clearer where the issue is. In fact, you may want to separate out the serialization/deserialization aspects to their own discrete method/class so you can feed in other serializers (or be more clear from the stack trace where the issue is, or simply to make your methods do one thing and one thing only) But any more rewriting/refactoring is really left for code-review anyway and not valid much for the question at hand.

    FYI, I also put a null check for your input object because if the user passes null, they would think that the save was successful when in fact, nothing happened and they might expect a value to be available for loading later when it doesn’t exist. If you want to allow nulls as valid values, then don’t bother with the check throwing an error.

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

Sidebar

Related Questions

I have a generic class that takes a type T . Within this class
If I have a class with a constructor that takes a parametized generic type:
I have a Java class that takes a generic type parameter and a class
I have generic type that looks like: public class GenericClass<T, U> where T :
I have a Base class that needs a Generic type. That can be either
I have a class which takes a type token, and then generates objects of
I have an interface which takes a generic type interface IIFace<T> Then i have
I have a generic class that needs to limit an enum depending on the
I have a Generic Base Class that I want to allow one of two
Suppose I have a Generic abstract class that provides some default constructor functionality so

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.