Pregunta

I'm having an object named data,which belongs to the class,

[DataContract]
public class names
{
    [DataMember(Name = "code")]
    public int Code { get; set; }

    [DataMember(Name = "message")]
    public string Message { get; set; }

    [DataMember(Name = "values")]
    public values values{ get; set; }
}

where values is another class with variables of its own, initially while executing the following code,

names data= new names();
data.values.Name = "";

I get a null exception when executing the second line.

What is the issue?Why data.values.Name is still null even after executing

names data= new names();

what should i do to give it some value?

¿Fue útil?

Solución

Initialize values also.

names data= new names();
data.values = new values();

Otros consejos

Aside from not naming your class object which is just asking for trouble. You can't access properties on values because you never initialized it. Your class needs a constructor where values is set to something. Or else you need to set values to something before you try and access it.

So either this:

[DataContract]
public class object
{
    [DataMember(Name = "code")]
    public int Code { get; set; }

    [DataMember(Name = "message")]
    public string Message { get; set; }

    [DataMember(Name = "values")]
    public values values{ get; set; }

    public object()
    {
        values = new values();
    }
 }

Or you could do:

 object data= new object();
 data.values = new values();
 data.values.Name = "";

Without context it's difficult to say which suits you better.

Ok, I'll stat by guessing the name object is only a bad name choice to illustrate your problem (as other said, you don't want to choose this name (if permitted).

The problem you are facing is that the Values property is not initialized, thus giving you an exception. Here is a sample of what you can do to avoid it:

public class MyObject
{
    public MyObject()
    {
        this.Values = new Values();
    }

    public int Code { get; set; }
    public string Message { get; set; }
    public Values Values { get; set; }
}

public class Values
{
    public string Name { get; set; }
}

As you can see, I initialize the Values property in the constructor of yout object.

taking your class:

[DataContract]
//I've renamed it to stop it hurting my eyes.
public class myClass
{
    [DataMember(Name = "code")]
    public int Code { get; set; }

    [DataMember(Name = "message")]
    public string Message { get; set; }

    [DataMember(Name = "values")]
    public values values{ get; set; }
}

If you change

myClass data= new myClass();
data.values.Name = "";

to:

myClass data= new myClass();
data.values = new values();
data.values.Name = "";

this will now work.

presuming:

public class values
{
   //empty constructor??
   public values()
   {

   }
   public string Name { get; set; }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top