DhavalR
DhavalR

Reputation: 1417

Properties are making trouble

In my application I have added a Properties.cs file which contains properties that I am would use through out the application. I am getting NullReferenceException => Object reference not set to an instance of an object.

Here is the code for Properties.cs

public class Properties
{
    private static string type1;

    public static string Type1
    {
        get
        {
            return type1;
        }
        set
        {
            type1= value;
        }
    }
}

And when I access this property in one of my form I am getting error. e.g.

if (Properties.Type1.Equals(string.Empty) || Properties.Type1.Equals(null))
{
    // Do something
}

Upvotes: 0

Views: 102

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1062855

Firstly, you're making life hard for yourself. This is fine (or at least, just as fine, but a lot easier; whether or not static members is a good idea is a separate question, and depends a lot on the context):

public class Properties
{   
    public static string Type1 { get;set; }
}

Secondly, this has nothing to do with properties, and everything to do with calling a method on a null instance. You can just use == which avoids this issue, i.e.

if (Properties.Type1 == "" || Properties.Type1 == null)
{
    // Do something
}

However, for convenience there is also string.IsNullOrEmpty:

if (string.IsNullOrEmpty(Properties.Type1))
{
    // Do something
}

Upvotes: 5

Alberto
Alberto

Reputation: 15941

You are doing the null and empty check in the wrong way.

The correct way is:

if (string.IsNullOrEmpty(Properties.Type1))
{
 ....
}

Upvotes: 2

David Pilkington
David Pilkington

Reputation: 13630

You can do this

if (String.IsNullOrEmpty(Properties.Type1))
{
    // Do something
}

but if you want a default value for this then I suggest you set it in a static constructor.

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391346

Use this instead:

if (string.IsNullOrEmpty(Properties.Type1))
{
    // Do something
}

Upvotes: 2

Related Questions