user1216456
user1216456

Reputation:

initializing a class using a property in c# -

I dont understand properties very well. the line of code: method2(x.str1, x.str2, x.str3, x.str4); --- throws me a "object reference not set to an instance of the object error". Any thoughts appreciated. x.str1 is not resolving?

(I am adding some code and adding more functionality to an existing set up. I would have initialized the class myProperty using methods and properties.)

using otherC#

   class Test{

    private myProperty x;

    private string  str1, str2, str3, str4;

    private myProperty A
            {

                get { return x; }          

                set
                {

                    str1 = value.str1;
                    str2 = value.str2;
                    str3 = value.str3;
                    str4 = value.str4;

                }             
            }

    public void myMethod()
        {

               Test tst = new Test();
               myProperty x = new myProperty();
               //Assigning property varaibles:
                  x.str1 = "this";
                  x.str2 = "is";
                  x.str3 = "my";
                  x.str4 = "test";

               try
                {

                    tst.method2(x.str1, x.str2, x.str3, x.str4);
                }
                catch(Exception)
                {
                    throw;
                }
            }

    public void method2(string str1, string str2,string str3, string str4)
     {
     }

    }

    OtherC#.cs  contains the definition for myProerty class

    namespace temp
    {
    public class xyx {some code;}
    public interface abc {some code};
    public class myProperty {

            public string str1 { get; set; }

            public string str2 { get; set; }

            public string str3 { get; set; }

            public string str4 { get; set; }
    }
    }

Upvotes: 0

Views: 240

Answers (2)

Steven Doggart
Steven Doggart

Reputation: 43743

A variable is just a reference to an object. It's not an object in and of itself. So the variable is null until you set it to reference an object. In this case you probably just want it to equal a new object, so you need to instantiate one. For instance, change this line:

private myProperty x;

to this:

private myProperty x = new myProperty();

I should clarify that this is only true of reference types (classes), not value types (structures).

Upvotes: 3

Matten
Matten

Reputation: 17603

myProperty x is not set to an instance of an object when you call

x.str1 = "this";

You have to intialize it first (in your constructor code, for example).

Upvotes: 5

Related Questions