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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T16:27:37+00:00 2026-05-26T16:27:37+00:00

How can I make sure that a certain instance of a class will never

  • 0

How can I make sure that a certain instance of a class will never be null? Someone told me to use Debug.Assert() but by doing so, I would only ensure that the code works in debug mode, whereas I want to ensure the is-never-null condition in release as well.

For example, in the past I wrote code like:

public string MyString
{
get
{
    if(instance1.property1.Equals("bla"))
    {
        return bla; 
    }
}
}

But this throws an exception if instance1 is null. I would like to avoid making such mistakes and generating such exceptions in the future.

Thanks,


please see a specific example below that illustrates the problem:

I have a method that authenticates users based on responses from a server. The method is this:

        /// <summary>
    /// attempts authentication for current user
    /// </summary>
    /// <returns></returns>
    public AuthResult CheckUser()
    {
        WebRequest request = WebRequest.Create(GetServerURI);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        string postdata = "data=" + HttpUtility.UrlEncode(SerializeAuth());
        byte[] arr = Utils.AppDefaultEncoding.GetBytes(postdata);
        request.ContentLength = arr.Length;
        request.Timeout = Convert.ToInt32(TimeUtils.GetMiliseconds(10, TimeUtils.TimeSelect.Seconds));

        Stream strToWrite = request.GetRequestStream();
        strToWrite.Write(arr, 0, arr.Length);

        WebResponse response = request.GetResponse();
        using (Stream dataFromResponse = response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(dataFromResponse))
            {
                string readObj = reader.ReadToEnd();
                return DeserializeAuth(readObj);
            }
        }
    }

to call this method, i use

_authenticationResult = authObj.CheckUser();

I also have this property, among others

        public ResultType AuthResult
    {
        get
        {
            if (_authenticationResult.auth == "1")
                return ResultType.Success;
            if (_authenticationResult.auth == "0")
                return ResultType.FailAccountExpired;
            if (_authenticationResult.auth == "-1")
                return ResultType.FailWrongUsernameOrPassword;
            if (_authenticationResult.auth == "-2")
                return ResultType.Banned;


            return ResultType.NoAuthDone;
        }
    }

public enum ResultType { Success, FailWrongUsernameOrPassword, FailAccountExpired, NoAuthDone, Banned }

what happened was that _authenticationResult was null once, and the property AuthResult threw a nullref at attempting “null.auth”. How can I ensure (perhaps inside the CheckUser() method) that it never returns null.

When i debugged the app it never happened. But in production, when the server timed out sometimes the method returned null.

Thanks,

  • 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-26T16:27:38+00:00Added an answer on May 26, 2026 at 4:27 pm

    I think you need to understand how instance1, and subsequently property1 are going to be instantiated, and only instantiate them in such a way that they cannot be null. This is generally done by checking arguments at construction, e.g.:

    public instance1(string property1)
    {
        if (property1 == null) throw new ArgumentNullException("property1");
    
        this.property1 = property1;
    }
    

    If you create your types in such a way that they cannot exist in an invalid state, you ensure that your dependent code won’t fall over on null values.

    Otherwise, we’d need to see a fuller example of what you are doing to give you more concrete advice.

    The other thing to consider, is what state your class can exist in which is a required state of operation, vs. an optional state of operation. That being, what members are required for your class to operate, and you should endeavour to design your classes such that they always have the required state, e.g.:

    public class Person
    {
      public Person(string forename, string surname)
      {
        if (forename == null) throw new ArgumentNullException("forename");
        if (surname == null) throw new ArgumentNullException("surname");
    
        Forename = forename;
        Surname = surname;
      }
    
      public string Forename { get; private set; }
      public string Surname { get; private set; }
    }
    

    In my example type, I’m requiring that my Forename and Surname value have a non-null value. This is enforced through my constructor… my Person type can never be instantiated with null values (although, perhaps empty values are just as bad, so checking IsNullOrWhiteSpace and throwing an appropriate ArgumentException is the route, but lets keep it simple).

    If I were to introduce an optional field, I would allow it to mutate the state of my Person instance, e.g., give it a setter:

    public class Person
    {
      public Person(string forename, string surname)
      {
        if (forename == null) throw new ArgumentNullException("forename");
        if (surname == null) throw new ArgumentNullException("surname");
    
        Forename = forename;
        Surname = surname;
      }
    
      public string Forename { get; private set; }
      public string Surname { get; private set; }
    
      public string Initial { get; set; }
    }
    

    My Person type still enforces the required fields for operation, but introduces an optional field. I then need to take this into consideration when performing an operation which uses these members:

    public override ToString()
    {
      return Forename + (Initial == null ? String.Empty : " " + Initial) + " " + Surname;
    }
    

    (Although that is not the greatest example of a ToString).

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

Sidebar

Related Questions

How can I make sure that a certain OLEDB driver is installed when I
I need to make sure that user can run only one instance of my
How can i make sure that several divs are slided up? Right now I
I would like to make sure that an applescript can be converted to bash.
How can I make sure in the following code snippet that IDataReader is disposed
How can I make sure that only users with an accelerometer sensor can download
How can I make sure the CS generated from code like the following is
How can I make sure setup.py compiles projects PO files and include them whenever
How can i make sure my file serving is reliable and scalable? How many
When using the function imagepng() in PHP, how can I make sure the images

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.