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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T11:31:06+00:00 2026-05-25T11:31:06+00:00

I have a method that generically deserializes a stored object from a users provided

  • 0

I have a method that generically deserializes a stored object from a users provided filepath and object type. The method works fine, except for when the user provides an invalid filepath. I would like my method to return a null in this case, but when I attempt to return null I get a compilation error. I tried to use a nullable type but get a compilation error. Instead, I typecast an object and return that, but it causes a runtime error. I would like to know if anyone knows the proper way to allow for returning a null. The code is as follows:

        public static T RestoreObj<T>(string datafile)
    {


        try
        {
            var fs = File.OpenRead(datafile);
            var bf = new BinaryFormatter();
            var obj = (T) bf.Deserialize(fs);
            fs.Close();
            return obj;
        }
        catch (Exception e)
        {
            MessageBox.Show("Could not load. Accepts valid *.dom files only. " + e);

            // TODO: how to do this? this will throw a runtime error, and if null returned, a compilation error
            var o = new object();
            return (T) o;
        }
    }

After taking Eric Lippert’s quality comments in to consideration I revised the method to look like what you see below. The advantage of using ‘using’ is that it automatically generates a try..finally block that will call the dispose method (FileStream implements IDisposable, if it did not their would be a compile error). Another nice thing is that the exception thrown is relevant to whatever is actually happening instead of what I have above.

        public static T RestoreObj<T>(string datafile) 
    {
        using (var fs = File.OpenRead(datafile))
        {
            var bf = new BinaryFormatter();
            var obj = (T)bf.Deserialize(fs);
            return obj;
        }
    }
  • 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-25T11:31:07+00:00Added an answer on May 25, 2026 at 11:31 am

    I would solve the problem by not writing that code in the first place.

    A method should do one thing and do it well; you are mixing up deserialization code with error reporting code.

    Don’t do that. A better way would be to have the deserialization method throw an exception, and write different code that handles the exceptions and reports errors to the user.

    More generally, it is dangerous to have a method that eats exceptions and then returns bogus data. That is just creating problems down the line when unsuspecting code that calls your method expects to get good data back.

    While we’re on the subject of code quality, you should be using “using” blocks to ensure that the file handles are closed if an exception happens. Do not explicitly do a fs.Close() — rather, do using(var fs = ... ) and let the compiler generate the disposal that closes the file.

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

Sidebar

Related Questions

I have a method that can return either a single object or a collection
I have a method that creates a MessageDigest (a hash) from a file, and
I have class method that returns a list of employees that I can iterate
I have a method that where I want to redirect the user back to
I have a method that takes an IQueryable. Is there a LINQ query that
I have a method that periodically (e.g. once in every 10 secs) try to
I have a method that's about ten lines of code. I want to create
I have a method that needs to accept an array of country names, and
I have a method that, given an angle for North and an angle for
I have a method that I'm writing that is calling another overloaded method inside

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.